1

Can someone tell me how to use Dynamic Allocation for char array, when I don't have the size of the input upfront?

2
  • 6
    Allocate some memory; use that much, and if its not enough allocate some more (with realloc). Commented Jan 2, 2021 at 20:03
  • Where are you getting your input from? This will effect the design choice. Commented Jan 2, 2021 at 21:43

1 Answer 1

2

You have to allocate memory and then reallocate. Here an example:

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

int main(void) {

    //allocate a buffer of 10 pointers
    size_t array_size = 10;
    char ** array=(char **)malloc(array_size * sizeof(*array) );
    if (!array)
        return -1;

    //now allocate the 10 pointers with a buffer to hold 42 characters
    for (int i = 0; i < array_size; i++) {
        array[i]= (char *)malloc( 42 * sizeof (*array[i]) );
        if (!array[i])
            return -1;
        strcpy(array[i], "10");
    }

    //for some reason we need to increase array size by 1
    ++array_size;
    array = (char **)realloc(array, array_size * sizeof(*array) );
    array[array_size-1] = (char *)malloc(42 * sizeof(*array[array_size-1]) );
    if (!array[array_size-1])
        return -1;
    strcpy(array[array_size-1], "12");
}
Sign up to request clarification or add additional context in comments.

Comments

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.