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

23

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?

This question is tagged with c pointers

~ Asked on 2011-09-02 07:29:04

The Best Answer is


22

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]);

~ Answered on 2011-09-02 07:34:49


7

Most people responding don't even seem to know what an array pointer is...

The problem is that you do pointer arithmetics with an array pointer: ptr + 1 will mean "jump 5 bytes ahead since ptr points at a 5 byte array".

Do like this instead:

#include <stdio.h>

int main()
{
  char (*ptr)[5];
  char arr[5] = {'a','b','c','d','e'};
  int i;

  ptr = &arr;
  for(i=0; i<5; i++)
  {
    printf("\nvalue: %c", (*ptr)[i]);
  }
}

Take the contents of what the array pointer points at and you get an array. So they work just like any pointer in C.

~ Answered on 2011-09-02 08:02:38


Most Viewed Questions: