re3el
re3el

Reputation: 785

Initialize a dynamic array in C

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!

Upvotes: 1

Views: 199

Answers (1)

Purag
Purag

Reputation: 17061

The function you're looking for is calloc.

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

char * str = calloc(length, sizeof(char));

Upvotes: 3

Related Questions