Looking for creating a dynamic array of string values.
The code example below was supposed to add a new array element (realloc) and a new line ("line 3"), which will be added to the array at runtime.
I assume the problem is pointers being misused and / or something wrong with realloc logic?
Appreciate any help.
Actual output I get:
Before:
Array[0]: string 1
Array[1]: string 2
After:
Array[0]: string 1
Array[1]: string 2
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **myArray;
main(int argc, char *argv[])
{
int i = 0;
myArray = malloc(2 * sizeof(char*));
int arrayIndexs = sizeof(*myArray) / sizeof(char*);
for (i = 0; i <= arrayIndexs; i++)
myArray[i] = malloc(254 * sizeof(char*));
if(myArray != NULL)
{
strcpy(myArray[0], "string 1");
strcpy(myArray[1], "string 2");
}
printf("Before: \n");
for (i = 0; i <= arrayIndexs; i++)
printf("Array[%d]: %s\n",i, myArray[i]);
myArray = (char **)realloc(myArray, sizeof(myArray)*sizeof(char*));
myArray[arrayIndexs+1] = malloc(254 * sizeof(char*));
strcpy(myArray[arrayIndexs+1], "string 3");
arrayIndexs = sizeof(*myArray)/sizeof(char*);
printf("After: \n");
for (i = 0; i <= arrayIndexs; i++)
printf("Array[%d]: %s\n",i, myArray[i]);
}
source
share