KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I know how to create an array of structs but with a predefined size. However is there a way to create a dynamic array of structs such that the array could get bigger? For example: typedef struct { char *str; } words; main() { words x[100]; // I do not want to use this, I want to dynamic increase the size of the array as data comes in. } Is this possible? I've researched this: words* array = (words*)malloc(sizeof(words) * 100); I want to get rid of the 100 and store the data as it comes in. Thus if 76 fields of data comes in, I want to store 76 and not 100. I'm assuming that I don't know how much data is coming into my program. In the struct I defined above I could create the first "index" as: words* array = (words*)malloc(sizeof(words)); However I want to dynamically add elements to the array after. I hope I described the problem area clearly enough. The major challenge is to dynamically add a second field, at least that is the challenge for the moment. I've made a little progress however: typedef struct { char *str; } words; // Allocate first string. words x = (words) malloc(sizeof(words)); x[0].str = "john"; // Allocate second string. x=(words*) realloc(x, sizeof(words)); x[1].FirstName = "bob"; // printf second string. printf("%s", x[1].str); --> This is working, it's printing out bob. free(x); // Free up memory. printf("%s", x[1].str); --> Not working since its still printing out BOB even though I freed up memory. What is wrong? I did some error checking and this is what I found. If after I free up memory for x I add the following: x=NULL; then if I try to print x I get an error which is what I want. So is it that the free function is not working, at least
Tags (comma-separated)
Save Edits
Cancel