String array in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Osoascam
    New Member
    • Feb 2007
    • 21

    String array in C

    Hi! I was looking for some help on this matter and found this: http://bytes.com/forum/thread643133.ht ml which... I didn't 100% got.

    So... I'll try to explain what I need:
    array[0] = "First string"
    array[1] = "Second string"
    array[2] = "This is the third one"
    .
    .
    .
    array[n] = "Hola"
    I have a dynamic array of fixed-length strings. At the very beginning I create it on a struct, like this:

    Code:
      char* datoString[CHARMAX];
      char nombre[CHARMAX];
    Where CHARMAX is, let's say, 30. So it's an array of strings of 29 characters + \0.

    Then, I discover the size of datoString (given by user) and I try to to this:

    Code:
    datoString = calloc(sizeGivenByUser, sizeof(nombre));
    I know I'm mixing nombre and datoString, but I dind't know how to get "sizeof(arr ay datoString[CHARMAX]".

    I don't know if I'm being clear...

    If the user says "12", then the array would be char[12][30], but... How do I do that dinamycally and how do I allocate memory?

    Please heeeeeelp :'(

    And thanks in advance ;)
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    Ditch the code you have now. You don’t even have the datatype down correctly, so any algorithm you have right now is flawed.

    So, we work backwards. You want to store n strings of some fixed size, like 30. The entire storage system has to be done dynamically, because you do not know the actual size at compile time.

    A string can be pointed to with a char*. Then you want many of these strings, in an array of unknown size. So what is this datatype? Start with the individual item in the array. It’s a char*, right? Because each char* points to a string. So you have array char* someArr[]. You need a pointer for this datatype. Remember how you point to arrays, with a pointer to its element. So if you have a char* element, it’s a char** pointer.

    Therefore, in your code, start with a char** pointer. Figure out how many strings you want. Then dynamically allocate an array of char*, with said length. Now you have an array of char*, each of which can be pointed somewhere. Each one needs to be point a C string. So loop over your char* array, and for each item in the array, point the char* at another dynamically created array of characters.

    You have to go through this two-step allocation sequence. When freeing the memory up, you also have to go through a two-step sequence. Free up each individual string. Then free up the array of pointers to the strings.

    If at any point, you do not understand why I said something, ask. This is a confusing topic, and you must be clear on why you do every step.

    Comment

    Working...