简体   繁体   中英

Initializing a malloc'ed string index to NULL

For example, say I just created a char **strings by using malloc.

How would I set each index strings[i] to NULL? Is it initially set to NULL? Because when I check with another function for an index equal to NULL, like if(strings[i] == NULL); It never seems to work. Any help? Sorry I'm new to dynamic memory..

NULL is usually defined as a macro that expands to (void *)0

You can use calloc to allocate and initialize to zero. Be sure to use the correct number of parentheses.

char* buffer = calloc(4, sizeof(char));

if(*buffer == 0) {
    printf("%s\n", "*buffer == 0");
}

malloc() only allocates memory. You should use calloc() which allocates memory and zeroes the allocated memory.

Being an array of pointers, each element will now be equal to NULL .

char **strings = calloc(1024, sizeof *string);
if(strings[1] == NULL)
    printf("%s", "yes. NULL");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM