簡體   English   中英

緩沖區到陣列(分段錯誤)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM