Helpful Information
 
 
Category: Computer Programming
dynamic 2d arrays in C

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

the probelm is that you have to free avery column
use this


for(i=0;i<col;i++)
free(*(A+i));

thanks for the reply but on my machine it still gives the error..

and i think it may be i<row
but that still gives an error

i<row gives an error when row > col

what compiler do you use. I us MSCV++

i think its called gcc
well thats the command i give it to compile programs

I've heard of it, but I don't have it installed :(

I compiled the app with GCC,and I got no errors when I ran it and entered a Col bigger than the Row.

I don't know if gcc can compile C++ code? if so, you can allways try the new and delete operators. they basicly do the same as malloc and free.


#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=new char *[row];

for(i=0;i<row;i++)
A[i]=new char[col];

for(i=0;i<row;i++)
delete []A[i];

return 0;

}

nah, new and delete come up as errors on gcc (which is what I have to use).

A = (char **)malloc(row * sizeof(char *));

for(i=0; i < col ; i++)
*(A+i) = (char *)malloc(col * sizeof(char));
Is there an error here! In the initial line you allocate "row" number of "slots", then your for loop tries to create "col" number of entries in the "row" number of slots.
But you only have a "row" number of slots to allocate and hence you get memory access errors when col > row!

cool it works now
thanks alot

this damn thing was driving me crazy, now i can continue my project to create wumpus world ugh,,...


thx

Originally posted by maes
I don't know if gcc can compile C++ code?

Sure it can,just make sure that your file has .cpp as extension.Heres an example command for compiling a C++ app:
gcc -o test test.cpp










privacy (GDPR)