C programming: pointer assignment only in main()?

  • Thread starter nobahar
  • Start date
  • #1
495
2
Hello,

I was assigning a pointer to an array and I noticed it will only this to takeplace within the main function:
Code:
#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:
#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.
 

Answers and Replies

  • #2
rcgldr
Homework Helper
8,768
565
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.
 
  • #3
495
2
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.

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...)
 
  • #4
495
2
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:
char *mssg;
...
int main( void ){
     mssg = "Hello";
...}
But not:
Code:
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:
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:
char *mssg = "Hello";
finds room for the string and tells mssg to point to it.

Any clarification would be very much appreciated!
 
  • #5
rcgldr
Homework Helper
8,768
565
does the (I assume) compiler "know" that the pointer is not initialised and puts the string somewhere where there is free memory
No, the program needs to initialize the pointer by pointing to an array or by allocating space for an array.

I imagine
Code:
char *mssg = "Hello";
finds room for the string and tells mssg to point to it.
In this case the literal string is "initialized" at compile time, as well as the pointer.
 
  • #6
35,121
6,862
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:
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:
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.
 
  • #7
AlephZero
Science Advisor
Homework Helper
7,002
293
To add to the above, when you write a string like "hello" in C, this is really just a shorthand for something like

Code:
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:
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:
printf("Hello");
In the code for printf, the parameter is defined as a pointer to a char.

I am under the impression the code is "read" from top-to-bottom (kind of),
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:
  • #8
495
2
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:

Code:
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.

Why does the following not follow the same pattern:
Code:
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...
 
  • #9
35,121
6,862
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:
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()?
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:
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.


I assume it has something to do with scope that alephzero mentioned.
No, nothing to do with scope. Variables declared outside of other functions have global scope within that file.
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
495
2
Many thanks for the responses!
 

Related Threads on C programming: pointer assignment only in main()?

Replies
28
Views
2K
  • Last Post
Replies
7
Views
3K
Replies
6
Views
5K
  • Last Post
Replies
7
Views
4K
Replies
6
Views
2K
  • Last Post
Replies
2
Views
6K
  • Last Post
Replies
20
Views
4K
  • Last Post
Replies
1
Views
690
Top