1

How do I achieve the dynamic equivalent of this static array initialization in C?

char c[] = {}; // Sets all members to '\0';

In other words, create a dynamic array with all values initialised to the termination character. Is the below method correct? Is there any better method?

str = (char*)malloc(length*sizeof(char));
memset(str, 0, length);

Thanks!

2
  • 1
    your first piece of code is setting a char to 0 instead of a char array... {} actually is not a array initializer but a more general. it can be used to initialize primitives, structs, unions, and of course array of them. Commented Aug 15, 2015 at 5:33
  • ^yup... I'm assuming OP meant char c[]. Commented Aug 15, 2015 at 5:37

1 Answer 1

3

The function you're looking for is calloc.

In your case, you'd use it as such:

char * str = calloc(length, sizeof(char));
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.