C programming: pointer assignment only in main()?

In summary: The first assignment assigns the string "Hello" to the pointer world, and the second assigns the value of the pointer hello to the variable world.
  • #1
nobahar
497
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.
 
Technology news on Phys.org
  • #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.
 
  • #3
rcgldr said:
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
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
nobahar said:
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.

nobahar said:
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
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
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
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:

Mark44 said:
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
nobahar said:
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.


nobahar said:
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.
nobahar said:
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
Many thanks for the responses!
 

1. What is pointer assignment in C programming?

Pointer assignment in C programming is the process of assigning a value or address to a pointer variable. This allows the pointer to point to a specific location in the computer's memory.

2. Can pointer assignment only be done in the main() function?

Yes, in most cases, pointer assignment can only be done in the main() function. This is because the main() function is the entry point of a C program and is responsible for initializing variables and allocating memory. However, pointers can also be assigned in other functions if they are passed as arguments.

3. What is the purpose of pointer assignment in C programming?

The purpose of pointer assignment in C programming is to manipulate and access data efficiently. Pointers allow us to directly access and modify data in a computer's memory, which can be useful for tasks such as dynamic memory allocation, data structures, and passing data between functions.

4. Can a pointer be assigned to a variable of a different data type?

Yes, a pointer can be assigned to a variable of a different data type. However, it is important to ensure that the data type of the pointer matches the data type of the variable it is pointing to in order to avoid unexpected errors or data corruption.

5. Are there any potential issues to consider when using pointer assignment in C programming?

Yes, there are some potential issues to consider when using pointer assignment in C programming. One common issue is pointer misuse, which can lead to memory leaks, segmentation faults, and other errors. It is important to properly allocate and free memory when using pointers to avoid these issues.

Similar threads

  • Programming and Computer Science
Replies
9
Views
7K
  • Programming and Computer Science
Replies
4
Views
729
  • Programming and Computer Science
Replies
17
Views
1K
  • Programming and Computer Science
Replies
3
Views
721
  • Programming and Computer Science
Replies
5
Views
872
  • Programming and Computer Science
Replies
6
Views
2K
  • Programming and Computer Science
Replies
14
Views
2K
  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
Replies
9
Views
998
  • Engineering and Comp Sci Homework Help
Replies
3
Views
744
Back
Top