Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Differences in using between *array2[0] and **arrays

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading