I cannot get it work.
The function returnPointer() returns pointer for every string I've inserted until it returns null value. I want to store all of these returned pointers in a dynamic array named arrayOfPointers in the way that I can print out all these stored strings later. The main function doesn't work correctly. It just crashes (altough it seems to store some pointers in arrayOfPointers). I think that there is something wrong with variable q after passing through the while loop in the main function for the first time.
Code:#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char * returnPointer();
int main ( void )
{
char *q = NULL;
char **arrayOfPointers = NULL;
int size2 = 0;
int capacity2 = 0;
do
{
if ( size2 == capacity2 )
{
capacity2 += 1;
arrayOfPointers = realloc ( q, capacity2 + 1 );
}
q = returnPointer();
arrayOfPointers[size2++] = q;
//printf("%d\n",arrayOfPointers[size2]);
} while (q != NULL);
free(arrayOfPointers);
return 0;
}
char * returnPointer()
{
char *s = NULL;
int size = 0;
int capacity = 0;
int ch;
printf("Insert something\n");
while ( ( ch = getchar() ) != '\n' && ch != EOF )
{
if ( size == capacity )
{
char *save;
capacity += 5;
save = realloc ( s, capacity + 1 );
if ( save == NULL )
break;
s = save;
}
s[size++] = ch;
}
if ( size > 0 )
{
s[size] = '\0';
}
return s;
}