2D array using realloc two times

I read a text file which has information like

3 54 6
32 12 76
.........
65 32 56

3 integers every line, separated with spaces, many-many lines

With line 13 the code is working well
But I want to make it general replacing line 13 with 14 and later with 18
why calloc is working well, but realloc is not working ?
thank you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
unsigned char **Arr = 0;
int i, j, k, m, l, t;
i = 0;

File = fopen("s.txt", "r");
while (!feof(File)){
	Arr = (unsigned char **)realloc(Arr, (i + 1) *sizeof(unsigned char*));
	fgets(x, 20, File);
	if (feof(File))
		break;
	l = t = 0;

	Arr[i] = (unsigned char *)calloc(3, sizeof(unsigned char)); // working well
//	Arr[i] = (unsigned char *)realloc(Arr[i], 3 * sizeof(unsigned char)); //not working

	for (k = 0; k < strlen(x); k++)
		if (x[k] == ' '){
//			Arr[i] = (unsigned char *)realloc(Arrr[i], (t+1) * sizeof(unsigned char));
			for (int poz = l; poz < k; poz++)
				Arr[i][t] = Arr[i][t] * 10 + (x[poz] - 48);
			l = k + 1;
			t++;
			Arr[i][t] = '\0';
		}
	i++;
}
fclose(File);
Last edited on
Data in arr is uninitialized, that means Arr[i] is pointer to some random memory. You are trying to reallocate random memory. Hence crash. You are probably meant to use malloc, as realloc is used to reallocate existing memory to other place.
Ok, I've got the mistake.
and the solution seems to be to initializre something only to have a pointer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
File = fopen("NEs.txt", "r");
while (!feof(File)){
	Arr = (unsigned char **)realloc(Arr, (i + 1) *sizeof(unsigned char*));
	fgets(x, 20, File);
	if (feof(File))
		break;
	l = t = 0;
	Arr[i] = (unsigned char *)calloc(1, sizeof(unsigned char));
	for (k = 0; k < strlen(x); k++)
		if (x[k] == ' '){
		Arr[i] = (unsigned char *)realloc(Arr[i], (t+1) * sizeof(unsigned char));
		Arr[i][t] = '\0';
		for (int poz = l; poz < k; poz++)
			Arr[i][t] = Arr[i][t] * 10 + (x[poz] - 48);
		l = k + 1;
		t++;
		Arr[i][t] = '\0';
		}
	i++;
}
fclose(File);


thank you MiiNiPaa, I am so happy !
Last edited on
Topic archived. No new replies allowed.