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;
}
4
  • 1
    In what way dit it not work? Commented Oct 29, 2017 at 13:59
  • error: "variable-sized object may not be initialized", while creating character array; Commented Oct 29, 2017 at 14:01
  • 1
    Possible duplicate of C compile error: "Variable-sized object may not be initialized" Commented Oct 29, 2017 at 14:04
  • that is something regarding int array and there is no dynamic allocation in that @NothingNothing Commented Oct 29, 2017 at 14:30

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

always check return values
@kkk Fixed it. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.