-1

I don't understand what is wrong with the code below. It should malloc a 2D char array[5][30] (referred as LENGTH), pass it to a function and fill it with a string. It works just fine in the function; I can print it from there without any problem. But i cannot print even the first one from within the main() function (the application crashes if I try). Could somebody please explain what I am doing wrong?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH 5 
void fillArray(char array[][LENGTH]) {
    for (int i = 0; i < 5; i++) {
        strcpy(array[i],"Hi World");
    }
    for (int i = 0; i < 5; i++) {
        printf("%s\n",array[i]);
    }
}

int main() {
    char** array = (char**)malloc(5*sizeof(char*));
    for (int i = 0; i < 5; i++) {
        array[i] = (char*)malloc(LENGTH);
    }
    fillArray(array);
    printf("%s",array[0]);
    getchar();
    return 0;
}
Zoe
  • 27,060
  • 21
  • 118
  • 148

2 Answers2

0

From main() function you are passing double pointer array and catching with 2D array array[][LENGTH] which is not correct, just saying double pointer is not similar to 2D array & vice versa.

for your task in fillArray() use array of char pointer as a argument, how many ? LENGTH.

void fillArray(char *array[LENGTH]) { /* this is okay */
        for (int i = 0; i < 5; i++) {
                strcpy(array[i],"Hi World");/*now in `array[i]` you can store any no of char. */
        }
        for (int i = 0; i < 5; i++) {
                printf("%s\n",array[i]);
        }
}

Also casting malloc() is not required And once job is done at last don't forget to free the dynamically allocated memory by calling free() for each.

Achal
  • 11,821
  • 2
  • 15
  • 37
0

The basic problem is that your function expects a 2 dimensional array but that is not what you pass to the function.

In main you allocate a 1 dimensional array of pointers. Then for each of these pointers, you allocate a 1 dimensional array of chars. That is not a 2D array.

So your function doesn't get what it expects and therefore your program fails.

So instead of:

char** array = (char**)malloc(5*sizeof(char*));
for (int i = 0; i < 5; i++) {
    array[i] = (char*)malloc(LENGTH);
}

try this:

char (*array)[LENGTH] = malloc(5*LENGTH*sizeof(char*));

to get a correctly malloc'ed 2D array.

BTW:

I think you have a bug here

#define LENGTH 5
               ^
               I guess you want 30 instead of 5
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63