0

I have declared a global array, char *people[][2]. The purpose of this array is to hold people's first and last names in the form of:

people[0][0]          = "John"           people[0][1]          = "Smith"
people[1][0]          = "Frank"          people[1][1]          = "Jones"
...                                      ...
people[NumOfNames][0] = "Lisa"           people[NumOfNames][1] = "Murray"

Where NumOfNames is an integer variable calculated in a function within my program. Once this value has been stored for NumOfnames, how can I use malloc to allocate memory to people so that it is of size [NumOfNames]*[2]?

KOB
  • 4,084
  • 9
  • 44
  • 88
  • 1
    First, I guess the actual names aren't actually literal strings, but read from somewhere? Secondly, to handle your problem you need two loops, one nested inside the other, for the allocations. – Some programmer dude May 05 '15 at 22:48
  • @JoachimPileborg Yes, the names are read from a file. Would you mind elaborating on the nested loops idea? I'm very new to the `malloc` function. – KOB May 05 '15 at 22:50
  • 3
    Unless you really have to do it this way a better way is to use a struct that contains firstname and lastname. Then you only need a single dimension array to hold each person. And has the added advantage of being easily extendable for more person attributes (e.g. age, height, etc). You would just need to add more fields to the struct. – kaylum May 05 '15 at 22:51
  • `people[NumOfNames-1][0] = "Lisa"` ? – BLUEPIXY May 05 '15 at 22:52
  • `char *(*people)[2] = malloc(NumOfNames*sizeof(*people));` – BLUEPIXY May 05 '15 at 22:59
  • take a look at this stack overflow http://stackoverflow.com/questions/25984700/setup-a-2d-array-change-size-later-c/25984834#25984834 with an answer that provides a function for a 2D array area that is malloced as well as links to some additional resources. – Richard Chambers May 05 '15 at 23:20

1 Answers1

0

That's easy once you know the syntax for multidimensional arrays:

size_t peopleCount = ...;
char* (*people)[2] = malloc(peopleCount*sizeof(*people));

Note that people here is, as always for malloc()ed arrays, a pointer to the first element of the array, i. e. a pointer to an array of two pointers to char. The malloc() call simply allocates memory for peopleCount such elements. By using this pointer type, you can use the malloc()ed array exactly the same way as you use the people array in your question.

cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106