指向字符串的指针数组 [英] array of pointers to strings
问题描述
在C编程中,鉴于我们无法使用scanf()函数获取指向指针数组的值,但
in a C Programming its given that we can't get the values using scanf() function to array of pointers but
int main()
{
char *names[6];
int loop;
scanf("%s",names[1]);
printftf("\n%s",names[1]);
}
它正在工作,当我将输入作为程序输入时,我认为它正在存储输入,但是它将输出正确地打印为给定的输入.之后它给出了分段错误... 但是当我为获得6个字符而循环执行相同操作时
it is working ,when i give the input as program ,i think it is storing the input,but it prints the output correctly as the given input.after that it gives a segmentation fault... but when i do the same in a loop for getting 6 charecters
int main()
{
char *names[6];
int loop;
for(loop=0;loop<6;loop++)
scanf("%s",names[1]);
for(loop=0;loop<6;loop++)
printf("\n%s",names[1]);
}
它不起作用,请给我答案...
its not working please give me the answer...
推荐答案
问题是您没有为这些名称分配任何空间.如果要与scanf
一起使用,则需要初始化数组中的每个元素.
The issue is that you are not allocating any space for those names. You need to initialize each element in the array if you intend to use it with scanf
.
char* names[6];
for( int i = 0; i < 6; ++i )
names[i] = malloc( 256 * sizeof *names[i] ); // or some other max value
scanf( "%s", names[1] );
否则,这些 pointers 会指向您内存中的任意位置,而尝试读取/写入这些位置最终会导致 segmentation fault .
Otherwise those pointers will be pointing anywhere in your memory, and attempting to read/write those locations will eventually result in a segmentation fault.
这篇关于指向字符串的指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!