简体   繁体   English

遍历指针到char指针数组

[英]Iterate over pointer to an array of char pointers

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

The scheme you have is missing a derference. 您的方案缺少推论。 *arrayPtr + i is the address of the i-th element of the array. *arrayPtr + i是数组第i个元素的地址。 Meaning it's a char** . 表示它是一个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. 但是,那里的C无效,因为在定义指针时省略了数组大小。 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. 另外,请注意,您可以像Blagovest Buyukliev指出的那样使用下标运算符,但对运算符优先级感到厌倦。 It's (*arrayPtr)[i] and not *arrayPtr[i] . 它是(*arrayPtr)[i]而不是*arrayPtr[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM