[英]C: how to fill a table with fgets() if we don't know the length?
I'm trying to fill a table word by word with the method fgets().我正在尝试使用 fgets() 方法逐字填充表格。 I need to fill a table with words(max 25) that the user write step by step.我需要用用户逐步编写的单词(最多 25 个)填充表格。 The problem is that on my terminal if I do for exemple :问题是,在我的终端上,如果我这样做:
The output is:输出是:
So basically it just copy the last word for each input I've entered所以基本上它只是复制我输入的每个输入的最后一个词
I've tried to replace "tab[length] = line;"我试图替换“tab[length] = line;” with "strcpy(tab[length], line);"用“strcpy(tab[length], line);” but when I do this I've got a "Segmentation fault (core dumped)"但是当我这样做时,我遇到了“分段错误(核心已转储)”
#define NBRE_CHAR 256
int main(int argc, char const *argv[])
{
char* tab[25];
int length =0;
char line[NBRE_CHAR];
while(fgets(line,NBRE_CHAR,stdin) != NULL){
line[strlen(line)-1] = '\0'; // to delete \n
tab[length] = line;
length++;
}
for (int i = 0; i < length; i++)
{
printf("%s\n", tab[i] );
}
}
char* tab[25];
is an array of 25 pointers to characters (strings).是一个包含 25个字符(字符串)指针的数组。
With tab[length] = line;
使用tab[length] = line;
you asign the buffer line
to the array.您将缓冲区line
分配给数组。 But that doesn't copy the string.但这不会复制字符串。 As a result, all entries point to your single line buffer, which will have your last entered string.因此,所有条目都指向您的单行缓冲区,其中将包含您最后输入的字符串。
What you may want is:你可能想要的是:
char* tab[25];
//...
tab[length]= malloc(strlen(line)+1);
strcpy(tab[length], line);
This allocates memory for each string and then copies the contents of your buffer to this memory.这会为每个字符串分配内存,然后将缓冲区的内容复制到该内存中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.