1 Replies - 4102 Views - Last Post: 10 May 2010 - 07:39 AM Rate Topic: -----

#1 Goldenglove  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 10-May 10

Allocating memory for an array of strings.

Posted 10 May 2010 - 07:32 AM

I need to dynamically allocate memory for an array of strings (max. string length is fixed - 256 characters), but the number of strings is unknown beforehand. And this needs to be done without vectors, just using malloc/realloc.

Basically, the program looks something like this (no code, just the structure):
char a[256];

while (set of rules which determine how many strings will be entered)
{
  cin >> a;
  //here the realloc part should go, I guess
}


So, the user enters strings which are saved to an array until something happens and the "while" part of the program ends.

I'm very confused when it comes to pointers - how many asterisks I should put, what to write in the realloc part, etc., so help would be really appreciated.

Also, how would I delete such an array of string?

Is This A Good Question/Topic? 0
  • +

Replies To: Allocating memory for an array of strings.

#2 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3088
  • View blog
  • Posts: 19,136
  • Joined: 14-September 07

Re: Allocating memory for an array of strings.

Posted 10 May 2010 - 07:39 AM

What you have now is just one "C string". An array of C string would require a 2D array or a * if you're careful about the "bounds".


char** stringArray;

//get input for the number of strings
stringArray = malloc(sizeof(char*)*numStringsInputted);

//then iterate through and allocate 256 characters to each:
stringArray[i] = malloc(256*sizeof(char));


//do stuff


//iterate again, freeing each index
free(stringArray[i]);

//free the main handle
free(stringArray);


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1