dole_4
09-22-2002, 04:27 PM
hi
i am trying to make as part of a C program, a function that will create a dynamic 2d array (as in a 2d array with no initial set limits on row/column sizes, they will be input when the program is run). This array does not need to be square, but its limits will be 100x100 of chars.
I made some code, and it works fine, except when the column size (col) is bigger than the rowsize (row). Then it gives me an error : segmentation fault (core dumped). Here it the code -
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int main()
{
char **A;
int row, col, i;
/*int c=0, d=0;*/
puts("row=");
scanf("%d", &row);
puts("col=");
scanf("%d", &col);
A = (char **)malloc(row * sizeof(char *));
for(i=0; i < col ; i++)
*(A+i) = (char *)malloc(col * sizeof(char));
free(A);
return 0;
}
Any help on fixing/explaining why this occurs would be helpful.
Thanks
i am trying to make as part of a C program, a function that will create a dynamic 2d array (as in a 2d array with no initial set limits on row/column sizes, they will be input when the program is run). This array does not need to be square, but its limits will be 100x100 of chars.
I made some code, and it works fine, except when the column size (col) is bigger than the rowsize (row). Then it gives me an error : segmentation fault (core dumped). Here it the code -
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int main()
{
char **A;
int row, col, i;
/*int c=0, d=0;*/
puts("row=");
scanf("%d", &row);
puts("col=");
scanf("%d", &col);
A = (char **)malloc(row * sizeof(char *));
for(i=0; i < col ; i++)
*(A+i) = (char *)malloc(col * sizeof(char));
free(A);
return 0;
}
Any help on fixing/explaining why this occurs would be helpful.
Thanks