在这里真的很挣扎,无法弄清楚如何从数组中获取我的值。
我首先声明这个数组,我想保存一组数字。我不知道为什么尺寸是 64,我只是很沮丧并给了它一个尺寸。
char *numberList1[64];
然后我使用我找到的一些代码读取文件。
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
char string[100];
int counter = 0;
printf("\n\nEnter name of File 1: ");
scanf("%s", string);
fp = fopen(string, "r");
if (fp == NULL) {
printf("invalid filename of %s",string);
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, fp)) != -1) {
numberList1[counter] = line;
counter++;
}
现在,如果在 while
内说类似 printf("%s",numberList1[counter]);
的话,我会得到所有的数字。
但是,当我说出以下内容时,无论何时有数字,我都只打印出最后一项。 ( vector 长度)。
int j;
//vectorLength is the user-entered # of lines/numbers in the file.
for (j = 0; j < vectorLength; j++) {
printf("Writing out: %s \n", numberList1[j] );
//write(pipe1[WRITE], currentNum, bitSize+1);
}
即如果我有数字,1、2、3、4 我会得到:4 4 4 4
我做错了什么???我试图找到有关理解 C 中指针和数组的指南,但我无法弄清楚......
最佳答案
您没有准备发送到 getline()
的参数适本地。根据文档:
If *lineptr is set to NULL and *n is set 0 before the call, then
getline()
will allocate a buffer for storing the line. This buffer should be freed by the user program even if getline() failed.
您想要为每一行创建一个新的行缓冲区,并且您至少似乎希望 getline()
为您创建该缓冲区,因此,在每次成功读取之后,并且一旦您保存了返回数组中由 getline()
分配的缓冲区指针,将行指针清回 NULL,并将长度参数清回零:
char * line = NULL;
size_t len = 0;
while ((read = getline(&line, &len, fp)) != -1 && counter < 64)
{
numberList1[counter++] = line;
line = NULL; // <<==== ADDED
len = 0; // <<==== ADDED
}
free(line); // note: this is here because, though getline() failed, the
// documentation for the api mandates its presence.
关于c - 从 C 指针数组获取我的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153500/