Целый день пытаюсь создать двумерный массив, который расширялся бы по мере заполнения (т.е. с помощью realloc). Но программа все время вылетает с ошибкой. Методом тыка определил, что ошибка возникает из-за того, что я пытаюсь расширить массив, который относится к адрессу a[msize]
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <ctype.h>
int main() {
char c;
int sum = 0;
int msize = 0;
int nsize = 0;
int **a;
a = (int**)realloc(a,(msize + 1) * sizeof(int*));
while ((c = getchar()) != '.' && c != EOF)
{
if(isdigit(c))
sum = sum*10 + c - '0';
else if (c == ' ')
{
a[msize] = (int*)realloc(a[msize], (nsize + 1)*sizeof(int));
a[msize][nsize++] = sum;
sum = 0;
}
else if (c == ',')
{
nsize = 0;
msize++;
a = (int**)realloc(a,(msize + 1)*sizeof(int*));
}
}
getchar();
return 0;
}
Попробовал и через malloc выполнить задачу. Та же история! :(
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <ctype.h>
int main() {
char c;
int sum = 0;
int msize = 0;
int nsize = 0;
int **a;
a = (int**)malloc(1000 * sizeof(int*));
while ((c = getchar()) != '.' && c != EOF)
{
if(isdigit(c))
sum = sum*10 + c - '0';
else if (c == ' ')
{
a[msize] = (int*)realloc(a[msize], (nsize + 1)*sizeof(int));
a[msize][nsize++] = sum;
sum = 0;
}
else if (c == ',')
{
nsize = 0;
msize++;
}
}
getchar();
return 0;
}
a = (int**)realloc(a,(msize + 1)*sizeof(int*));
нечего перераспределять. Вa[msize]
не будет/может не быть указателя на существующий массив.int **a = NULL;