Why can’t we initialize a pointer variable with user defined input?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can initialize a pointer at the global scope to any value which is either a constant expression, or resolvable by the linker. This is because the C compiler places constants direct into the initialization code. Referenced symbols are also placed into the initialization code, and the linker replaces those symbols by the real address values.
In a function you can initialize any non-static pointer variable to a value which is already there. This is because these initializations work like normal variable assignments.
Edit: The illegal
int *baz = bar;partDisclaimer: I describe the behavior of typical compiler+linker toolchains seen on windows, Linux and *BSD, in the embedded world the initalization can look very different.
All initializations of variables on the global level are put into an own data segment in the executable file, and are copied at the program start into the RAM. This means that the linker must create this sections by collecting all global variables, and resolving symbol references in this section. The linker can only resolve values which contain link-time constant values only, which are addresses and numeric constants. The
int *baz = bar;statement does use an indirect value,bar. While bar can be resolved to&fooin this specific case, the compiler does not care, since the standard requires that this is an assignment ofbazwith the runtime memory content of bar. And since such runtime memory references are not available to the linker, since the linker can’t run the program, the compiler reject to generate code for this statement.Also changing the type of
barfromint* bartoint* const bardoes not help, because also a constant does have a memory region, and the C compiler must act as if it uses this memory region when the values is used somewhere. This means that even when it is clear which valuebardoes have, the compiler can’t place the constant value into object code, since the standard requires that the runtime memory is used to determine the value ofbarwhen it is used.As a side note, in C++ it is permitted to do initializations which are based on runtime data.