Search code examples
carraysdynamic-arrayscalloc

Dynamic String array dosent work


I'm trying to create a dynamic array of 1000 character long strings using calloc:

int i;
char** strarr =(char**)calloc(argc,sizeof(char)*1000);
if(strarr == NULL)
    return 0;
strarr[0][0] ='a';
printf("%c\n",strarr[0][0]);

Every time i try to run this code i get segmentation fault on the printf line, i don't get why does this happen (you can assume that argc is bigger than 0) Thanks

P.s. im sorry that the code is in text format but im using a mobile so i dont have the code feature


Solution

  • Try this:

    const int num_of_strings = 255; //argc ?
    const int num_of_chars = 1000;
    
    int i;
    char** strarr =(char**)malloc(sizeof(char*)*num_of_strings);
    
    if(strarr == NULL)
        return 0;
    for (i = 0; i < num_of_strings; i++) strarr[i] = (char*)malloc(sizeof(char)*num_of_chars);