I'm trying to understand the difference between pointers and arrays so I've created a simple program. All I'm doing is assigning a character to pointer pointing to a char. So as I know there is two methods for doing that. First one: by using the derefrence operator Second one: by using squares bracket
For more details let me provide the code
char **array2 = malloc(sizeof(char*));
*array2[0] = 'c';
The above seems not working
And the second version I've tried is this
char **array2 = malloc(sizeof(char*));
**array2 = 'c';
First, non of theses codes are working for me. Second, what are the differences between these two versions
CodePudding user response:
Syntactically, x[y]
and *(x y)
are exactly the same. So both pieces of code are doing the same thing. The problem is that you're trying to dereference an invalid pointer.
After the initialization, array2
pointer to a single object of type char *
which can be accessed as either array2[0]
or *array
. This pointer object is uninitialized. You then attempt to dereference this uninitialized pointer and assign a value to the dereferenced objects. Attempting to dereference an invalid pointer triggers undefined behavior.
You can fix this by either allocating memory for this pointer to point to:
char **array2 = malloc(sizeof(char*));
array2[0] = malloc(sizeof(char));
*array2[0] = 'c';
Which is equivalent to:
char **array2 = malloc(sizeof(char*));
*array2 = malloc(sizeof(char));
**array2 = 'c';
Or you get get rid of the extra level of indirection:
char *array2 = malloc(sizeof(char));
array2[0] = 'c';
*array2 = 'c';