0

Lets say I have the following code:

char *array[] = {"one", "two", "three"};
char *(*arrayPtr)[] = &array;

How do I iterate over array? I've tried doing this but doesn't work:

for(int i = 0; i < sizeof(array)/sizeof(array[0]); i++) {
    printf("%s\n", (*arrayPtr + i));
}
5
  • 1
    Any reason a plain array[i] can't be used by you? Commented Apr 4, 2017 at 5:26
  • @StoryTeller I have to pass the variable array as to pointer to a struct Commented Apr 4, 2017 at 5:27
  • First things first, if you think you need to take an array address as in &array, you are probably wrong. Commented Apr 4, 2017 at 6:12
  • @n.m. Could you please elaborate? Commented Apr 4, 2017 at 14:50
  • Pointers to arrays are rarely needed, mainly when they are elements of larger arrays (e.g with 2d arrays). In most cases a pointer to the first element of an array is more convenient and less confusing. Commented Apr 4, 2017 at 15:17

1 Answer 1

2

The scheme you have is missing a derference. *arrayPtr + i is the address of the i-th element of the array. Meaning it's a char**. You need to at least dereference that:

printf("%s\n", *(*arrayPtr + i));

However, that isn't valid C you have there, since you omitted the array size when defining the pointer. I hope it's not the actual code you wrote.

Also, note that you can use the subscript operator as Blagovest Buyukliev pointed out, but be weary of operator precedence. It's (*arrayPtr)[i] and not *arrayPtr[i].

Sign up to request clarification or add additional context in comments.

6 Comments

Alternatively, (*arrayPtr)[i].
Thanks a lot!! :)
Do you mean the array size when defining 'array' or 'arrayPtr'?
@SanketDeshpande - arrayPtr. It's a must have there. The size for array is deduced from the initializer, so no problem there.
@SanketDeshpande - That's a possibility yes. But personally, a plain char** that's passed with a size parameter seems less verbose.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.