Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pointer to char array, values in that array can be accessed?

Tags:

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?

like image 455
Pravi Avatar asked Sep 02 '11 07:09

Pravi


People also ask

How an array can be accessed using pointer?

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).

How do you access elements in a char array?

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 ++ .

What is a char pointer?

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.


1 Answers

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]); 
like image 142
nos Avatar answered Sep 28 '22 08:09

nos