I created ptr as pointer to an array of 5 chars.
char (*ptr)[5];
assigned it the address of a char array.
char arr[5] = {'a','b','c','d','e'}; ptr = &arr;
using pointer ptr can I access the char values in this array?
printf("\nvalue:%c", *(ptr+0));
It does not print the value.
In my understanding ptr will contain the base address of array but it actually point to the memory required for the complete array (i.e 5 chars). Thus when ptr is incremented it moves ahead by sizeof(char)*5
bytes. So is it not possible to access values of the array using this pointer to array?
The elements of 2-D array can be accessed with the help of pointer notation also. Suppose arr is a 2-D array, we can access any element arr[i][j] of the array using the pointer expression *(*(arr + i) + j).
Use the array subscript operator [] . It allows you to access the nth element of a pointer type in the form of p[n] . You can also increment the pointer by using the increment operator ++ .
char *p = "abc"; defines p with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.
When you want to access an element, you have to first dereference your pointer, and then index the element you want (which is also dereferncing). i.e. you need to do:
printf("\nvalue:%c", (*ptr)[0]);
, which is the same as *((*ptr)+0)
Note that working with pointer to arrays are not very common in C. instead, one just use a pointer to the first element in an array, and either deal with the length as a separate element, or place a senitel value at the end of the array, so one can learn when the array ends, e.g.
char arr[5] = {'a','b','c','d','e',0}; char *ptr = arr; //same as char *ptr = &arr[0] printf("\nvalue:%c", ptr[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With