1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C program: array of pointers

  1. Jul 29, 2004 #1

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I am not sure I wrote this correctly, but I am trying to declare an array of 12 pointers to arrays of 50 characters:

    char *names[12] [50]

    Does this look OK? Thanks.
     
  2. jcsd
  3. Jul 29, 2004 #2

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    arrays and sizes

    I am also not sure why this won't work when I am declaring two arrays.

    char ArrayOne[] = "Run, Spot, Run!";
    int length =strlen(ArrayOne);
    char ArrayTwo[length];

    I thought this would declare an array of characters (ArrayTwo)and make it the same length as ArrayOne?
    I errors like: "expected constant expression" and "cannot allocate an array of constant size 0"

    Why wouldn't this work? Thanks.
     
  4. Jul 29, 2004 #3
    For your first query,
    if you want just 12 pointers then char *names[12] would suffice.
    However it seems you want to 12 names with 50 characters at max in which case
    char names[12][50] would suffice.
    why? because the identifier "names" itself is a pointer.
    you can access any name just by,
    printf("%s",names). (for i betn 1 and 12).

    For your second query,
    you are not properly instantiating the character array,it should be ...

    char ArrayOne[] = "Run, Spot, Run!";
    int length =strlen(ArrayOne);
    char *ArrayTwo;
    ArrayTwo = new char[length];

    (i have assumed u are working with cpp)
    if u are working with C then use malloc instead of the new operator.

    -- AI
     
  5. Jul 29, 2004 #4
    You can not make an array of n dimentions where n is not constant e.g.

    int n=10; // not a constant
    char mychars[n]; // array of characters
    // Wrong

    This will result in "expected constant expression"

    However if it were

    const int n=10; // a constant (hence the "const" type)
    char mychars[n]; // array of characters
    // Correct

    You want to declare an array of n dimentions where n is the length of a string, right?

    Do this:

    #include <stdlib.h>
    char *mystring="Run, Spot, Run!";
    char *ArrayTwo=new char[strlen(mystring)];

    If you're using an old C/C++ compilier use this to be on the safe side:

    #include <stdlib.h>
    char *mystring="Run, Spot, Run!";
    char *ArrayTwo=(char*)malloc(strlen(mystring));

    Hope this helps.

    Mike
     
  6. Jul 29, 2004 #5

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks, AI. I am working with C. What does malloc do? I assume it allocates memory?

    -Jessica
     
  7. Jul 29, 2004 #6

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    And thank you, Mike. I will give that a try.

    p.s. I have found that I had to use the include
    #include <string.h>
    or I got warning messages from Visual C++ compiler. You don't have to use that include with your compiler?

    (This is when I am trying to use strlen() I mean. Sorry - I am not being very clear today! :redface: )
     
    Last edited: Jul 29, 2004
  8. Jul 29, 2004 #7
    Yes malloc allocates memory.

    Also yes u need #include<string.h> for using strlen().
    all the string related functions are defined in string.h
    these string functions include strlen,strcmp,strcmpi,strtok,strstr and so on....

    -- AI
     
  9. Jul 29, 2004 #8

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I had pretty good luck with your suggestions, but I did get a warning that "'malloc' is undefined; assuming extern returning int" so perhaps there is some library that I need to include in the header. I was getting the same warning with strlen() until I put #include <string.h> in the header.
    Here's what I have now.

    PHP:

    #include <stdio.h>
    #include <string.h>
    int main (void)
    {
    char ArrayOne[] = "Run, Spot, Run!";
    char *ArrayTwo=(char*)malloc(strlen(ArrayOne));
    return 0;
    }
     
     
  10. Jul 29, 2004 #9

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    ooh - found it!

    # include<malloc.h>

    thank you, Google! :biggrin:
     
  11. Jul 29, 2004 #10

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thank you, dear faraway friend! I appreciate your help.
     
  12. Jul 29, 2004 #11
    Don't know about us compiliers but for "string.h" + "alloc.h" all i include is "stdlib.h". It include the other two headers within it.
     
  13. Jul 29, 2004 #12
    What are you trying to do anyway?
     
  14. Jul 29, 2004 #13

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Hi Mike, as far as the "arrays and sizes" question, I am playing around with copying a string from one array to another - without using strcopy() . I was trying to figure out how I could make the second array the same size as my first one, then copy that characters over. I am not quite sure if that's the best way to go about it so I was just experimenting a little bit.
     
  15. Jul 29, 2004 #14

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Keep in mind that the size of an array and the length of a string in that array are not necessarily the same. In fact, they're rarely the same.

    If you want to create an array of a size determined only at runtime, you'll need to use the malloc() function (the old C way) or the new operator (the C++ way).

    - Warren
     
  16. Jul 29, 2004 #15

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks, Warren. I just started looking at the malloc() function. I am little bit baffled by the RHS of this still

    char *ArrayTwo=(char*)malloc(strlen(ArrayOne));

    I can see that the string length is returned inside the malloc() function, so is malloc() now setting aside bytes of space to hold the number of characters found by strlen()?
    Does malloc() then use the (char*) just before it to know what kind of objects it needs to make room for?

    p.s. I don't think I understand what the * after char means in (char*)
     
  17. Jul 29, 2004 #16
    If I remember correctly, malloc() returns void* which you must then cast to whatever pointer type you are using, in your case char*. You may be asking yourself: What is the purpose of casting pointers if they are all basically the same thing (i.e. memory addresses)? Think of it as some rudimentary C type-checking.
     
  18. Jul 29, 2004 #17

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    If my strlen() function counts the characters in the string and returns an integer value of 15, then malloc() has the integer value of 15 as an argument.. I think? Does malloc(15) then look at (char*) and interpret the whole thing as "OK I need to make space for 15 chars" ?

    what is void*? Is that a null pointer?

    Thanks!

    (sorry for such basic questions - I am having trouble reading further on in my book until I get a better understanding of this stuff)
     
    Last edited: Jul 29, 2004
  19. Jul 29, 2004 #18

    plover

    User Avatar
    Homework Helper

    Yes, strlen will return 15. However, to create a proper string with 15 text characters, you need to add one to that in order to have room for the terminating null character.

    A void* is a generic pointer. It is the built-in C mechanism for passing around an arbitrary memory address.

    malloc does not know what you want memory for -- it just knows that you want a certain amount. So it allocates the memory and gives you the pointer to the memory without according a specific type to the pointer. That is why it is proper to cast the return value to the appropriate pointer type.

    char* s2 = (char*)malloc(strlen(s1)+1);

    The cast (i.e. the "(char*)" in front of malloc) tells the compiler that while you know that the return value of malloc is not a char*, that you are sure that you want to treat it like one and thus that it is ok to assign the result to a variable of type char*.
     
    Last edited: Jul 29, 2004
  20. Jul 29, 2004 #19

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Ahhhh... Slowly the light-bulb is coming on!

    So malloc() is returning a pointer, then char* s2 is holding the address that was returned?

    Thanks, plover! You're a peach! :smile:
     
  21. Jul 29, 2004 #20

    plover

    User Avatar
    Homework Helper

    Code (Text):
    char ArrayOne[] = "Run, Spot, Run!";
    int length =strlen(ArrayOne);
    char ArrayTwo[length];
    This listing that you included above is correct C code -- but only if the compiler supports the most recent version of the C standard (known as C99). In VC++ version 6, I'm fairly sure that C99 is not supported. I don't know what support there is in the .NET version.

    The deal here is that earlier C standards required arrays to have a size that could be determined at compile time rather than run time. Thus, for older compilers
    char a[5];
    #define SIZE 12
    char b[SIZE];​
    are both ok, but
    int n = 5;
    char a[n];​
    is not.

    I think that also the C++ standard does yet not allow for these variable length arrays.

    As for include files: some compilers (such as GNU's gcc) have a few common C library functions (e.g. printf) built into the compiler, and thus no include directive is strictly necessary when using these functions. However, recognizing these functions without the include directive is non-standard behavior, so depending on this functionality for anything other than informal coding is generally a bad idea. I don't know if strlen is ever one of the built-in functions.

    It is also good coding practice not to rely on standard library headers to include other library headers for you.

    C pointer declaration syntax - the reason you are confused by this is that, well, it's confusing. :wink: This is not one of C's strong points...

    Traditionally C programmers have written pointer declarations like this:
    char *s;​
    That's because in multiple declarations each pointer requires its own '*':
    char *s, *t, *u, v;​
    (Note that v is just a regular char not a pointer.)

    I personally prefer this equally valid syntax:
    char* s;​
    which
    • emphasizes that 'pointer-to-char' is the type of s,
    • doesn't have the ambiguity of having *s meaning one thing in the declaration and another when used in later expressions, and
    • makes cast notation like (char*) make more sense.
    BUT, using this style means you have to take care never to write:
    char* s, t; /* Probably not what was intended */​
    and think you have two pointers.

    The ambiguity of the *s notation that I mentioned works like this:
    char t[] = "Go! See Spot debug!";
    char *s = t;
    *s = 'L';
    Warning: I'm not necessarily recommending that you adopt this style of notation. Notational issues like this are often the cause of religious wars among programmers. It is nearly always best to follow the conventions of whatever group of programmers you happen to be working with.

    On the other hand, it is also important to have your style of coding be clear to you. Also, it's good to be familiar with the variants as you may encounter them in other people's code.

    I better stop now... :redface:

    (How did I end up in this long and ridiculously didactic digression? :eek: I hope at least something in here is helpful...)
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: C program: array of pointers
  1. C++ Program Ideas (Replies: 9)

Loading...