0

I need to create character array at runtime because question input goes like this:

1. The first line contains , N the number of strings.

2. The next N lines each contain a string.

I tried creating 2-D array but it didn't work.

int main() {
    int n,count;
    scanf("%d",&n);

    for(int i=0; i<n; i++){
        char* arr[i]= char*(malloc(sizeof(char)));
    }

    return 0;
}
abhishekrn
  • 79
  • 8

1 Answers1

3

Do something like this:

#define STRINGSIZE 30;
int main() {
    int n,count;
    scanf("%d",&n);
    char **arr;
    arr = malloc(sizeof(char*) * n);

    for(int i=0; i<n; i++){
        arr[i]= malloc(sizeof(char) * STRINGSIZE);
    }

    return 0;
}

Explanation:

In C, you have pointers to access array. For a multidimensional array with variable lengths, its common to have pointer to pointers. So char **arr; arr = malloc(sizeof(char*) * n); means that you're creating an array of pointers to char. Then you need to call malloc for each of these pointers to allocate memory for each string.

Of course, you do not need to use a constant for string sizes. You can use a variable instead, and you can use different sizes for each string.

Note:

To avoid problems in the future if you want to change the array to an int array instead, do like this and you do not have to worry about changing on more places:

char **arr;
arr = malloc((sizeof a[0]) * n);
for(int i=0; i<n; i++){
    arr[i]= malloc((sizeof a[0][0]) * STRINGSIZE);
}

Also, do not cast malloc

And as kkk pointed out in the comments. Check return values.

arr = malloc(sizeof(char*) * n);
if (NULL == arr) {
    perror("Could not allocate memory");
    exit(EXIT_FAILURE);
}
klutt
  • 30,332
  • 17
  • 55
  • 95