简体   繁体   English

将 int 分配给数组时出现分段错误

[英]Segmentation Fault while assigning int to array

I am try to read a line from a file, separate the chars, and then read them to a malloc'ed int array.我尝试从文件中读取一行,分离字符,然后将它们读入 malloc 的 int 数组。 I seem to be getting a segmentation fault when I use atoi to cast the char to an int, and thus I am unable to assign the int to the array.当我使用 atoi 将 char 转换为 int 时,我似乎遇到了分段错误,因此我无法将 int 分配给数组。 Any help would be appreciated.任何帮助,将不胜感激。

int main(int argc, char * argv[]){

    FILE *in;
    in = fopen(argv[1], "r");
    FILE *out;
    out = fopen(argv[2], "w");

    int numDays;
    char ignore[256];
    fscanf(in, "%d", &numDays);
    fgets(ignore, sizeof(ignore), in);

    int *timeArray = (int *) malloc(numDays * sizeof(int)); ;

    char buffer[256];
    fgets(buffer, 256, in);

    const char delimiter[2] = " ";
    char *token;
    token = strtok(buffer, delimiter);
    int index = 0;
    while( token != NULL ) {
        printf( "%s\n", token);
        token = strtok(NULL, delimiter);
        int val = atoi(token);
        timeArray[index] = val;
        index++;
    }
    return(0);
}

When no tokens are left, strtok() returns NULL .当没有留下任何标记时, strtok()返回NULL But you call atoi(token) on it immediately, which will crash if it is NULL .但是你立即调用atoi(token) ,如果它是NULL就会崩溃。 The loop condition while (token != NULL) doesn't help because it isn't checked until the end of the loop body.循环条件while (token != NULL)没有帮助,因为直到循环体结束才检查它。

You need to restructure the loop so that the test is done before you try to use the result.您需要重组循环,以便在尝试使用结果之前完成测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM