Carlos Manrique Enguita Carlos Manrique Enguita - 23 days ago 8
C Question

Dynamic string matrix in C

I am having the next problem. I'm trying to create a dynamic matrix of strings which dimensions are defined by the user. The next code I made returns a segmentation fault:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
char ***pa = NULL;
int rows, columns , max, i, j = 0;

//Ask dimension
puts("Type number of columns: ");
scanf("%d",&columns);
puts("Type number of rows: ");
scanf("%d",&rows);
puts("Type max string length: ");
scanf("%d",&max);

//Allocate in memory
***pa = (char ***)malloc(rows * sizeof(char**));
for(i=0;i<rows; i++){
pa[i] = (char **)malloc(columns * sizeof(char*));
for(j=0; i<columns;j++){
pa[i][j] = (char)malloc((max+1)*sizeof(char));
}
}
puts("Memory OK");

//Fill the matrix
i = 0;
j = 0;
for(i=0;i<rows;i++){
strncpy(pa[i][j] , "Hello world", max);
for(j=0;j<columns;j++){
strncpy(pa[i][j] , "Hello world", max);
}
}

//Shows the matrix
for(i=0;i<rows;i++){
puts(pa[i][j]);
for(j=0;j<columns;j++){
puts(pa[i][j]);
}
}
//Cleans the matrix
free(pa);

return 0;
}


I know I should check if the returned pointer by malloc is NULL but I didn't included it yet.
The program does not print this so the problem is in the malloc for's

puts("Memory OK");


How can I debug this so I could know what happend? Did I made a mistake while coding it?

Answer

Change

pa[i][j] = (char)malloc((max+1)*sizeof(char));

into:

pa[i][j] = (char *)malloc((max+1)*sizeof(char));

Also, no need for the outer (first) strncpy in the main.

[EDIT]

Also, the first allocation line ***pa = ... should be pa = .... You want to assign an address to the pointer pa, not de-reference it (***pa de-references the pointer pa that has not been yet initialized).