I just read that we need to give the type of pointers while declaring them in C (or C++) i.e.:
int *point ;
As far as I know, pointers sto
One reason is in pointer arithmetic. You cannot do p+1
unless you know the size of the element to which p
points -- that is the size of the type to which p
is a pointer. If you'd try p+1
on a void *p
you're likely to get a bad answer (it is the same as if done on a char *
but maybe you didn't want that; it is caught by -pedantic
as a warning and by -pedantic-errors
as an error).
Another reason is type safety. If a function receives as argument an int *
you cannot pass a pointer to char
(a string) there. You'd get a warning (an error with -Werror
/ -pedantic-errors
). Consider this (dummy) code:
void test(int *x)
{
}
int main()
{
char *x = "xyz";
test(x);
return 0;
}
Compiling (using gcc (GCC) 4.8.2 20131017 (Red Hat 4.8.2-1)
) gives:
1.c: In function ‘main’:
1.c:8:2: warning: passing argument 1 of ‘test’ from incompatible pointer type [enabled by default]
test(x);
^
1.c:1:6: note: expected ‘int *’ but argument is of type ‘char *’
void test(int *x)
^