Dynamicaly allocating memory for unknown number of strings of unknown sizes in c
Hello everyone nice to meet you , new member on this site.I would apreciate your help to finish a program i am working on , what i am trying to do is allocate memory for an unknown number of strings of unknown sizes.The problem is that i am missing something in my logic with pointers and the program crashes (probably i am not allocating righly).Thank you in advance and excuse my english.https://cboard.cprogramming.com/images/icons/icon7.png
Here is the code:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* GetString();
void StoreStrings(char ***storage,int *size);
int main()
{
char **strings = NULL;
int size,i;
StoreStrings(&strings,&size);
for(i=0;i<size;i++)
{
printf("%s\n",strings[size]);
}
system("PAUSE");
return 0;
}
char* GetString()
{
char *string = NULL,c;
int size = 1;
string = (char*)malloc(size+1);
string[size-1] = '\0';
while((c = getchar()) != '\n')
{
string[size-1] = c;
size++;
string = (char*)realloc(string,size+1);
string[size-1] = '\0';
}
return string;
}
void StoreStrings(char ***storage,int *size)
{
char *string = NULL;
*size = 0; //number of strings set to 0
*storage = (char**)malloc((*size+1) * sizeof(char*)); //allocating memory for the number of the strings
*storage[*size] = (char*)malloc(sizeof(char)); //allocating memory for the string size of the 1st string (i use malloc here because i have read that you should call malloc first and then use realloc)
string = GetString(); //reading a string
while(strcmp(string,"") != 0) //if user gives empty string storing proccess ends
{
*storage[*size] = (char*)realloc(*storage[*size],(strlen(string)+1) * sizeof(char)); //reallocating memory for the string (+1 is for '\0')
strcpy(*storage[*size],string); //storing the string
(*size)++; //updating the number of strings
*storage = (char**)realloc(*storage,(*size+1) * sizeof(char*)); //reallocating memory for the updated number of strings
string = GetString(); //reading new string
}
free(string);
}