Forgive me if this is a simple error, but I am just learning C at the moment and I just made a trivial program to get a grasp of pointers.
I have a simple piece of code that yields an output I expect
int x = 4;
int *p;
p = &x;
printf("%d\n\n",*p);
//output is 4 as expected
But when I try to do the same with a char array even though I follow the same logic…
char x[] = "Hello, Stack Overflow!";
char *p[];
p = &x;
printf("%s\n\n",*p);
//this gives me an error when compiling as follows
//
// run.c:15: error: incompatible types when assigning to type ‘char *[1]’ from type ‘char (*)[23]’
Multiple errors. First,
char *p[]doesn’t declare a pointer-to-an-array (as you think it does) – it rather declares an array of char pointers.Second, since
xis an array,&xwill evaluate to the same numerical value asx(since arrays cannot be passed by value, only by pointer, they decay into pointers when passed to a function). What you need to do is ratherThis is the easy solution (making the string literal, that is, an array of
chars, decay into a pointer). There’s another solution that requires a bit more thinking. From the compiler error message, you can see that the type of&xischar (*)[]. So what you have to declare here is a pointer-to-array: