'Set the last value of a dynamic array of char pointers in C to NULL for while loop termination?
I have a few questions based off the code below.
- Would this be the correct way to have a sentinel value of NULL at the end of this dynamic array of char pointers? If not what could I do?
- Will the code below cause a memory leak because I am setting malloced memory to NULL?
My general question would be.
- What could I possibly do so that I can have a dynamic array of character pointers with the last value to be NULL so I can stop the loop at that point without keeping a count of how many elements in the dynamic array of character pointers.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
char **array_strings = NULL;
array_strings = malloc(sizeof(char *) * 2);
array_strings[0] = malloc(sizeof(char) * 5);
strcpy(array_strings[0],"test");
array_strings[1]=NULL;
while (array_strings[i] != NULL)
{
printf("array_strings[%d]: %s", i, array_strings[i]);
i++;
}
free(array_strings[0]);
free(array_strings[1]);
free(array_strings);
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
