c - 在二维数组中使用指针

标签 c arrays 2d fault

我试图将从文件(使用单独的函数)读取的整数数组存储在二维数组中,但我一直遇到段错误问题。我知道这是我的指针的问题,但我无法弄清楚我到底做错了什么。

这是我的函数(获取一个整数并将其与从文件中读取的整数进行比较,然后将其存储在我的二维数组中)。

int **getStopTimes(int stop_id) {

int **result = malloc(sizeof(*result)); 
char const* const fileName = "stop_times_test.txt"; 
FILE* txt = fopen(fileName, "r"); 
char line[256];
int count = 0;

while (fgets(line, sizeof(line), txt) != NULL) {    
        int *formattedLine = getStopTimeData(line); //getStopTimeData returns a pointer to an array of ints, memory is allocated in the function
        if (formattedLine[1] == stop_id) {
            result[count] = formattedLine;
            count++;
        }                           
}       
fclose(txt);
return result;  
}

我的主要内容:

int main(int argc, char *argv[]) {
int **niceRow = getStopTimes(21249);
for (int i=0; i<2; i++) { //Only looping 3 iterations for test purposes
    printf("%d,%d,%d,%d\n",niceRow[i][0], niceRow[i][1], niceRow[i][2], niceRow[i][3]);
}
free(niceRow);
return 0;
}

正在调用的 getStopTimeData 函数(从字符数组中提取某些信息并将其存储/返回 int 数组):

int *getStopTimeData(char line[]) {
int commas = 0;
int len = strlen(line);
int *stopTime = malloc(4 * sizeof(*stopTime)); //Block of memory for each integer
char trip_id[256]; //Temp array to build trip_id string
char stop_id[256]; //Temp array to build stop_id string
int arrival_time; //Temp array to build arrival_time string 
int departure_time; //Temp array to build departure_time string 
int counter;

for(int i = 0; i <len; i++) { 
    if(line[i] == ',')  {
        commas++;
        counter = 0;
        continue;
    }
    switch(commas) { //Build strings here and store them 
        case 0 : 
            trip_id[counter++] = line[i]; 
            if(line[i+1] == ',') trip_id[counter] = '\0';
            break;
        case 1: //Convert to hours past midnight from 24hr time notation so it can be stored as int
            if(line[i] == ':' && line[i+3] == ':') {
            arrival_time = (line[i-2]-'0')*600 + (line[i-1]-'0')*60 + (line[i+1]-'0')*10 + (line[i+2]-'0'); 
            }   
            break;
        case 2 : 
            if(line[i] == ':' && line[i+3] == ':') {
            departure_time = (line[i-2]-'0')*600 + (line[i-1]-'0')*60 + (line[i+1]-'0')*10 + (line[i+2]-'0');
            }       
            break;
        case 3 : 
            stop_id[counter++] =  line[i];
            if(line[i+1] == ',') stop_id[counter] = '\0';
            break;
    }
}
//Assign and convert to ints
stopTime[0] = atoi(trip_id);
stopTime[1] = atoi(stop_id);
stopTime[2] = arrival_time;
stopTime[3] = departure_time;
return stopTime;
}

最佳答案

这一行:

int **result = malloc(sizeof(*result));

只为一个指针分配内存。 (*result 的类型为 int *,因此它是一个指向数据的指针——sizeof 运算符会告诉您指向数据的指针的大小数据...例如 32 位架构上的 4)

如果没有看到 getStopTimeData() 的代码,我并不完全清楚你想要做什么......但你肯定需要更多的内存。如果这个函数确实返回一个指向某些int的指针,并且它正确地处理分配,那么您可能需要类似这样的东西:

int result_elements = 32;
int **result = malloc(sizeof(int *) * result_elements);
int count = 0;

[...]
    if (formattedLine[1] == stop_id) {
        if (count == result_elements)
        {
            result_elements *= 2;
            result = realloc(result, result_elements);
        }
        result[count] = formattedLine;
        count++;
    }

添加适当的错误检查,mallocrealloc 可能返回 (void *)0(又名 null)内存不足的情况。

此外,初始分配大小的 32 只是一个疯狂的猜测...根据您的需要进行调整(这样它不会浪费大量内存,但对于大多数人来说已经足够了)用例)

关于c - 在二维数组中使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32641903/

相关文章:

JavaScript效率: big object vs many arrays

java - 数组中的数组 : iteration doesn't recognize strings inside of it

c# - 在二维网格中查找所有循环/封闭形状

java - 可用于安卓游戏的最佳 2D 动画格式是什么

c - C中的二维字符数组初始化

c - 使用cygwin终端在c中打印数字的幂

arrays - 如何将字符串附加到 Bash 数组的每个元素?

java - 测试失败,我做错了什么?

c - popen2 : reading works, 写入不

c - C 中的正则表达式匹配和打印