[英]Buffer to array (segmentation fault)
我正在尝试打开一个文件,一行一行地读取内容(不包括空行),并将所有这些行存储在一个数组中,但是似乎无法解决该问题。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char buffer[500];
FILE *fp;
int lineno = 0;
int n;
char topics[lineno];
if ((fp = fopen("abc.txt","r")) == NULL){
printf("Could not open abc.txt\n");
return(1);
}
while (!feof(fp))
{
// read in the line and make sure it was successful
if (fgets(buffer,500,fp) != NULL){
if(buffer[0] == '\n'){
}
else{
strncpy(topics[lineno],buffer, 50);
printf("%d: %s",lineno, topics[lineno]);
lineno++;
printf("%d: %s",lineno, buffer);
}
}
}
return(0);
}
考虑到“ abc.txt”包含四行(第三行为空),如下所示:
b
2
4
我一直在尝试几种方法,但现在我所得到的只是细分错误。
这主要是因为您试图将读取的行存储在长度为0的数组中
int lineno = 0;
int n;
char topics[lineno]; //lineno is 0 here
更正上述错误后,您的程序中还会有更多错误。
strncpy()
需要使用char*
作为其第一个参数,然后您将其传递给char
。
如果要存储所有行,则以array[0]
为第一行, array[1]
为下一行,则需要一个char指针数组。
像这样
char* topics[100];
.
.
.
if (fgets(buffer,500,fp) != NULL){
if(buffer[0] == '\n'){
}
else{
topics[lineno] = malloc(128);
strncpy(topics[lineno],buffer, 50);
printf("%d: %s",lineno, topics[lineno]);
lineno++;
printf("%d: %s",lineno, buffer);
}
注意:使用main()
的标准定义
int main(void) //if no command line arguments.
奖金
由于您不小心踩到了长度为0的数组 ,因此请在此处进行阅读。
这个声明一个可变长度的数组
int lineno = 0;
char topics[lineno];
无效,因为数组的大小可能不等于0,并且在程序/上下文中没有意义
您可以为char *
类型的char *
动态分配一个数组,并在每次添加新记录时重新分配。
例如
int lineno = 0;
int n;
char **topics = NULL;
//...
char **tmp = realloc( topics, ( lineno + 1 ) * sizeof( char * ) );
if ( tmp != NULL )
{
topics = tmp;
topics[lineno] = malloc( 50 * sizeof( char ) );
//... copy the string and so on
++lineno;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.