C语言 在 c 中打印出字符串数组的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14306867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print out elements of an array of strings in c
提问by turnt
I've created a function that takes a pointer to the first element in a C-String array. This is the array, and how I went about making it:
我创建了一个函数,它接受一个指向 C-String 数组中第一个元素的指针。这是数组,以及我如何制作它:
char element1[60] = "ubunz";
char element2[60] = "uasdasffdnz";
char* array[10] = {element1,element2};
Then I created a pointer to the first element in the array:
然后我创建了一个指向数组中第一个元素的指针:
char *pointertoarray = &array[0];
Then I passed the pointer to the function I made:
然后我将指针传递给我创建的函数:
void printoutarray(char *pointertoarray){
int i = 0;
while (i < 2){
printf("\n Element is: %s \n", *pointertoarray);
pointertoarray = pointertoarray + 1;
i = i+1;
}
}
When I run the program the array never prints out.
当我运行程序时,数组永远不会打印出来。
I've done this program before in C++ but I used the STL string type, and made a pointer to an array of strings. I think my problem lies with the way I'm going about making an array of strings in C, and making a pointer to it.
我之前用 C++ 完成了这个程序,但我使用了 STL 字符串类型,并创建了一个指向字符串数组的指针。我认为我的问题在于我在 C 中创建一个字符串数组并创建一个指向它的指针的方式。
回答by John Vulconshinz
When printf() is called with %s it will more or less do the following
当使用 %s 调用 printf() 时,它或多或少会执行以下操作
for(i = 0; pointer[i] != 'for(i = 0; pointer[i] != 'void printoutarray(char *pointertoarray)
{
for(i = 0; i <= 2; i++)
{
printf("\n Element is: %s \n", pointertoarray[i]);
}
}
'; i++)
{
printf("\n Element is %c", pointer[i]);
}
'; i++)
{
printf("%c", pointer[i]);
}
What you want do is something like
你想做的是
char *pointertoarray = &array[0];
When you are referencing specific elements in an array you must use a pointer AND an index i.e. pointer[0] in this case 0 is the index and 'pointer' is the pointer. The above for loops will move through the entire array one index at a time because 'i' is the index and 'i' increases at the end of every rotation of loop and the loop will continue to rotate until it reaches the terminating NULL character in the array.
当您引用数组中的特定元素时,您必须使用指针和索引,即在这种情况下,指针[0] 0 是索引,而“指针”是指针。上面的 for 循环将在整个数组中一次移动一个索引,因为 'i' 是索引,而 'i' 在循环的每次旋转结束时增加,并且循环将继续旋转直到到达终止的 NULL 字符数组。
So you might want to try something along the lines of this.
所以你可能想尝试一些类似的东西。
printf("\n Element is: %s \n", pointertoarray);
回答by gustaf r
Does this:
做这个:
##代码##compile without warnings on your compiler? If so, your compiler is broken. Please read the errors and warnings it prints out.
在你的编译器上编译没有警告?如果是这样,你的编译器坏了。请阅读它打印出来的错误和警告。
&array[0]is a char**, not a char*
&array[0]是一个char**,不是一个char*
回答by hmatar
Remove the asterisk
去掉星号
##代码##
