Loading symbols into a dynamically allocated 2D array
This may be one of the common questions, but all the solutions I've seen so far don't work. I want to dynamically allocate a 2D array of characters. I am getting these symbols from a .txt file. I even set the number of rows (int r) and columns (int s). Self-allocation works, but whenever I try to load symbols from a file into this array, it crashes. I do not know why.
The file is ordered like this:
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
Opening the desired file:
FILE* file;
file = fopen(argv[1], "r");
if (file == NULL) {
printf("Error occurred when loading the file, program quits now.");
return 1;
} else {
printf("File loaded successfully.");
}
Getting information about the number of columns and rows (r - rows, s - columns):
int r,s,i,j;
char arrayInfo[6];
fgets (arrayInfo, 6, file);
char* comma = strchr(arrayInfo, ',');
s = atoi(comma - 1)+1;
r = atoi(comma + 1);
Memory allocation for a two dimensional character array:
char **array = malloc(r * sizeof(char *));
for(i=0;i<r;i++){
array[i] = malloc(s * sizeof(char));
}
DOES NOT WORK Loading symbols from a file and then printing them. This code will work with char [r] [s]; "instead of dynamic selection.
for (j=0;j<r;j++) {
for (i=0;i<s;i++) {
array[i][j] = fgetc (file);
}
}
for (j=0;j<r;j++) {
for (i=0;i<s;i++) {
printf ("%c",array[i][j]);
}
}
return 0;
}
source to share
If there is a glitch, I doubt the problem is related to:
array[i] = malloc(s * sizeof(char));
Please make sure malloc () succeeds or not first and then try to write to that allocated memory.
a[i][j]
i
is your row and j
is your column. We can see that it has been replaced in your code.
I don't know what your file looks like, but please check below again.
s = atoi(comma - 1)+1; /* comma is a pointer and you are decrementing it by 1? */
,
used in strchr and then the pointer is decremented by 1 to get an integer value, which is not what you want. Correct this as well.
source to share