Can someone please explain to me what\'s wrong with the following, and more importantly why?
int main( int argc, char *argv[] )
{
char array[] = \"array\
This would be the way to do what you seem to be trying to do:
int main( int argc, char *argv[] )
{
char array[] = "array";
char (*test)[6];
test = &array;
(*test)[0] = 'Z';
printf( "%s\n", array );
return 0;
}
test is a pointer to an array, and an array is different from a pointer, even though C makes it easy to use one like the other in my cases.
If you wanted to avoid having to specify a specific sized array, you could use a different approach:
int main( int argc, char *argv[] )
{
char array[] = "array";
char *test;
test = array; // same as test = &array[0];
test[0] = 'Z';
printf( "%s\n", array );
return 0;
}
char **test;
is a pointer to a pointer, but if you're going to take the address of an entire array then it needs to be a pointer to entire array i.e char (*test)[6];
test = &array
is wrong because test is of type char**
and &array
is a char(*)[6]
and is a different type from char**
An array isn't the same type as char*
although C will implicitly convert between an array type and a char*
in some contexts, but this isn't one of them. Basically the expectation that char*
is the same as the type of an array (e.g: char[6]
) is wrong and therefore the expectation that taking the address of an array will result in a char**
is also wrong.