Beginner struggling with pointer and string arrays

Discussion in 'C Programming' started by Riaan C, Oct 11, 2003.

  1. Riaan C

    Riaan C Guest

    Hi

    I'm new to C. Here's the problem. I understand the whole concept of
    pointers and can easily use it with normal non-array variables.

    I want to declare a array of strings, thus multidimensional character
    array, in my int main();

    Then I want to pass this to a function that will scanf all the values.
    I also want another function to display all the names but I just can
    get it working.

    How do yo do it?

    Thanks

    Riaan
     
    Riaan C, Oct 11, 2003
    #1
    1. Advertisements

  2. Riaan C

    osmium Guest

    Fill in the blanks.

    #include <stdlio.h> // exit()

    void chat(char t[][20])
    {
    }
    /*-------------------------*/
    void display(char u[][20])
    {
    }
    /*-------------------------*/
    int main()
    {
    char s[3][20];
    chat(s);
    display(s);
    }
     
    osmium, Oct 11, 2003
    #2
    1. Advertisements

  3. Riaan C

    Micah Cowan Guest

    No, more likely you want to declare an array of *pointers* to
    strings. An array of strings is awkwards if the strings are of
    different lengths, since you would still be forced to allocate
    exactly the same amount of space for each string.

    (Example of an array of strings:)

    char aos[][6] = {
    "Hello",
    "there",
    "bud"
    };

    As you can see, "bud" above still gets 6 bytes even though it
    only uses 4 (counting the terminating null character). Compare
    with:

    (Example of an array of pointers-to-string:)

    char *aopts[] = {
    "Hello",
    "there",
    "bud"
    };

    The disadvantage to the above is that you must either point the
    strings to string literals (as above), in which case you
    shouldn't try to modify them; or you need to dynamically
    (probably) allocate space for each and every element (and,
    therefore, free() them also).
    I'm not sure what exactly you mean here. Please explain in more
    detail what you wish to do.

    -Micah
     
    Micah Cowan, Oct 12, 2003
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.