Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C programming: pointer assignment only in main()?

  1. Dec 21, 2013 #1
    Hello,

    I was assigning a pointer to an array and I noticed it will only this to takeplace within the main function:
    Code (Text):
    #include <stdio.h>

    float array_1[10] = { 1,1,2,3,4,5,6,7,8,9 };
    float * p_array_1;

    int main( void )
    {
        p_array_1 = &array_1;
        printf("array address using ampersand is %p and using element one is %p, and using pointer is %p", &array_1, &array_1[0], p_array_1);
        printf("\nfloat size is %d", sizeof(float));

        return 0;
    }
     
    If I tried:
    Code (Text):
    #include <stdio.h>

    float array_1[10] = { 1,1,2,3,4,5,6,7,8,9 };
    float * p_array_1;
    p_array_1 = &array_1;

    int main( void )
    {
        printf("array address using ampersand is %p and using element one is %p, and using pointer is %p", &array_1, &array_1[0], p_array_1);
        printf("\nfloat size is %d", sizeof(float));

        return 0;
    }
     
    Why is this the case? Surely, once the array is declared it has an assigned place in memory; as such, the pointer can be assigned the arrays address. I am under the impression the code is "read" from top-to-bottom (kind of), and so the array is assigned a place in memory early on. I do not understand why I have to wait until main() to initialise the pointer.

    Any help appreciated.
     
  2. jcsd
  3. Dec 21, 2013 #2

    rcgldr

    User Avatar
    Homework Helper

    Outside of a function, you can declare the initial value, although the syntax looks like an assignment:

    float * p_array_1 = array_1;

    Note that & is not use before array_1, since C treats an array name similar to a pointer.
     
  4. Dec 23, 2013 #3
    Thanks rcgldr!

    (The textbook I am working through makes it clear the array name is a pointer, that was a boo boo on my part...)
     
  5. Dec 23, 2013 #4
    As a related issue, I noticed with character strings, which essentially arrays of type char(?), and pointers I can do this (The ... just means "other code"):
    Code (Text):
    char *mssg;
    ...
    int main( void ){
         mssg = "Hello";
    ...}
    But not:
    Code (Text):
    char *mssg;
    mssg = "Hello";
    ... int main( void ){...}
    This is a similar situation to the above. Is the first method acceptable? I know that it is necessary to be wary when using uninitialised pointers, e.g.:
    Code (Text):
    char *mssg;
    int main( void ){
        ... gets(mssg);
        ... }
    In this case gets() might store the input string to the "address" in the uninitialised mssg pointer, which could be pointing to anywhere. In the first example, where a message is only assigned in main and not immediately when the mssg pointer is declared, does the (I assume) compiler "know" that the pointer is not initialised and puts the string somewhere where there is free memory and then changes where mssg points - namely, to the string; or is this not safe to do? I imagine
    Code (Text):
    char *mssg = "Hello";
    finds room for the string and tells mssg to point to it.

    Any clarification would be very much appreciated!
     
  6. Dec 23, 2013 #5

    rcgldr

    User Avatar
    Homework Helper

    No, the program needs to initialize the pointer by pointing to an array or by allocating space for an array.

    In this case the literal string is "initialized" at compile time, as well as the pointer.
     
  7. Dec 23, 2013 #6

    Mark44

    Staff: Mentor

    To expand on what rcgldr said, the first example below is OK, but the second is likely to cause an exception at run time.

    Code (Text):
    char *mssg;
    ...
    int main( void ){
         mssg = "Hello";
    ...}
    In the example above, mssg is declared but not initialized with a known memory address. The line of code with mssg = "Hello"; resets the value in mssg to the address in memory where the compiler has stored the string.

    Code (Text):
    char *mssg;
    int main( void ){
        ... gets(mssg);
        ... }
    [/quote]
    As before, mssg is an uninitialized pointer variable. In the call to gets(), whatever characters you type in get stored at the memory location that mssg represents. Since the pointer variable still has whatever garbage value in it that it started with, the code for gets will store the input characters at that location. Doing so could overwrite some of your own variables or go into memory that your program doesn't own. Either way, this is not a good thing.
     
  8. Dec 23, 2013 #7

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    To add to the above, when you write a string like "hello" in C, this is really just a shorthand for something like

    Code (Text):

    char an_array_with_no_name[6] = { 'H', 'e', 'l','l','o',0};
     
    except you can't use the array explicitly in your program, because it has no name! The only way you can use it is by making a pointer variable point to it, either when you define the pointer or assign a value to it, as in
    Code (Text):

    char* hello = "Hello";
    char* world;
    ....
    world = "Stop it, I want to get off";
     
    or you can use it as an argument to a function, as in
    Code (Text):

    printf("Hello");
     
    In the code for printf, the parameter is defined as a pointer to a char.

    That is "kind of" true :smile:

    But don't read too much into that. I'm guessing you are just starting to learn C, and it's hard to explain the "correct" version of this until you know a bit more about the language. (If you want to "read ahead", look up the scope of variable names, and also the difference between defining and declaring variables. These are very important ideas, but you have to learn to walk before you can run!
     
    Last edited: Dec 23, 2013
  9. Dec 26, 2013 #8
    Thanks for the feedback everyone. This is the part that still confuses me, sorry if the answer is in one of the responses, I can't seem to put the pieces together:

    Why does the following not follow the same pattern:
    Code (Text):
    char *mssg;
    mssg = "Hello";
    ...
    int main( void ){
    ... return 0;}
    The mssg pointer is declared but not initialised, but in the next statement why can't the value in mssg change and point to the address for the string "Hello", just as it did inside main()?
    I assume it has something to do with scope that alephzero mentioned. I recently covered an introductory chapter to scope in the textbook. In this case, the pointer mssg is declared as a global variable, visible to all functions in the source code file; when it points to a string, this occurs in main. Leaving aside my confusion as to what effect this has on the other functions beside main() and how they see the pointer mssg - I guess I could try writing code to see -, I am at a loss as to why directing mssg to the string can occur in main() but not as a statement immediately following the declaration of the pointer.

    Any help much appreciated.
    Nobahar is confused. I also have a pending question for a new thread...
     
  10. Dec 26, 2013 #9

    Mark44

    Staff: Mentor

    That's exactly what happens. In the first line, mssg is declared. Since you haven't set its value to anything, it will have some random value in it. In the second line above, mssg is reset to what "Hello" evaluates to, which is an address - the address in memory of the first character in the string.
    Keep in mind that the value of a pointer variable is a memory address. If you change the value of a pointer variable, you change the location it points to.

    As I mentioned before, the following code has a problem.
    Code (Text):
    char *mssg;
    int main( void ){
        ... gets(mssg);
        ...
    }
    The similarity between this code and the preceding code is that mssg starts off uninitialized in both cases. Where the two code samples are different is that in the sample here, mssg never gets its value changed. As mssg is uninitialized, it is pointing to some random byte in memory. When gets() is called, it starts storing characters at that memory location, and this will very likely overwrite other variables in your program or be in memory locations that your program isn't allowed to use. Either way, this sample (with gets()) is a bad idea.


    No, nothing to do with scope. Variables declared outside of other functions have global scope within that file.
     
  11. Dec 31, 2013 #10
    Many thanks for the responses!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C programming: pointer assignment only in main()?
  1. C++ assignment (Replies: 7)

Loading...