Ошибка сегмента C Программа Dynami c 2D массив для базы данных социальных сетей - PullRequest
0 голосов
/ 28 марта 2020

2 дня без прогресса. Я получаю ошибку сегмента, когда пытаюсь печатать на коде CLion или Visual Studio, но не на других онлайн-компиляторах ... почему? Как исправить: https://repl.it/join/epycryqd-joelortiz: здесь работает нормально. Я пытаюсь создать базу данных социальных сетей, которая требует динамического распределения памяти c. Я разбираю следующий файл input.txt. У user_IDS есть # после идентификатора, они будут размещены все вертикально в первом столбце. Список друзей пользователей будет без # и будет помещен после первого столбца в строке.

Подводя итог:

  • ИД пользователя первого столбца .horizont.
  • Все строки пользователей друзья. вертикальный.

Мой код работает на любом онлайн-компиляторе, но никак не на другом ..... приводит к ошибке сегмента и куче нулей ....... что происходит не так?

input.txt

123456#
654321#
000007#
000666#
000007 123456
000666 000007
000111#
987654#
654321 000111
987654 000111

Мой код:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char * argv[])
{
    FILE * input_file = fopen(argv[1], "r");
    int number;
    char str[100];
    // read every string from input file
    int **ptr; // to store the user and his/her friends in multi-dimensional array
    // first column stores user ID and rest of the column stores his friend list
    int *row; // to store the number of columns in each row
    int rowSize = 2; // inital size
    ptr = (int **)malloc(sizeof(int *) * rowSize); // allocating memory
    row = (int *)malloc(sizeof(int) * rowSize);
    int i = -1; // to keep track of current row
    int colSize = 2; // initial size of col, we increment if it gets full
    int j = 0; // to keep track of col
    while(fscanf(input_file, "%s", str) != EOF)
    {
        //check if the string has '#' at the end then the take characters before the # and convert it to integer
        if(i == rowSize)
        {
            rowSize *= 2;
            ptr = realloc(ptr, rowSize*sizeof(int*));
            row = realloc(row, rowSize*sizeof(int));
        }
        if(str[strlen(str) - 1] == '#')
        {
            if(i != -1)
            {
                row[i] = j;
            }
            j = 1;
            i++;
            colSize = 2;
            ptr[i] = (int *)malloc(colSize*sizeof(int));
            sscanf(str, "%d", &number);
            ptr[i][0] = number;
        }
        else if(str[strlen(str) - 1] != '#')
        {
            if(j == colSize)
            {
                colSize *= 2;
                ptr[i] = realloc(ptr[i], rowSize*sizeof(int));
            }
            sscanf(str, "%d", &number);
            ptr[i][j] = number;
            j++;
            //row[i] = j;
        }
    }

    fclose(input_file);
    printf("Format\n");
    printf("[User ID] -> [Friend1], [Friend2] . . .\n\n");
    for(int ii = 0; ii <= i; ii++)
    {
        printf("%d -> ", ptr[ii][0]);
        for(int jj = 1; jj < row[ii]; jj++)
            printf("%d, ", ptr[ii][jj]);
        printf("\n");
    }
    return 0;
}

1 Ответ

0 голосов
/ 28 марта 2020

Одна проблема состоит в том, что когда j == colSize, вы удваиваете colSize, а затем изменяете размер ptr[i] на основе rowSize. Это использует неправильную переменную.

...