Question:
Can you explain pointers to me? (Programming C)?
Clare
2017-03-13 01:51:24 UTC
Can someone explain pointers to me for programming in C? I have a few questions:

1. why must we assign a new variable to the address of another variable instead of use the address directly?

2. I am especially wondering why the variable that designed inside of a function(class) cannot be accessed outside of the class?
Four answers:
Richard
2017-03-13 20:05:15 UTC
1) There are two reasons for passing an address of a variable into a function that you are calling:



a) All you can pass into a function is a single word for each parameter. So if you want to pass an array or a structure into the function, you cannot simply pass the whole array or structure and all you can do is pass the address of that data component - the address will be a single word.



char buffer[256]; // This is a character array of 256 characters.



You can call a function by simply using



function (buffer); // buffer is the address of the array buffer[256].



struct

{

int value;

char name[32];

} my_structure;



In this case you would use



function (&my_structure);



You can define a pointer (an address variable) such as:



struct

{

int value;

char name[32];

} my_structure, *str_ptr;



str_ptr = &my_structure;

function (str_ptr);



2) When you call a function (C does not use classes), variables passed to the function as parameters in the function call are loaded on to the program's stack and are accessed by the function from the stack. When the function returns to the calling code sequence, the locations on the stack are available for reuse. The data may be accessible on the stack, but even an interrupt being taken at the wrong moment can reuse the stack locations and change the data that the function was using. By passing an address in the function call, the function can update the variables directly in the calling function. Local variables used in a C program and its functions are also stored on the stack, so the same thing applies when a function returns and the stack locations it was using are released and can be reused.



I hope this helps.
mark_poc
2017-03-13 19:52:11 UTC
The reason a variable that was designed inside of a function cannot be accessed outside of the function is because it was designed to be that way. The compiler purposely makes the variables hard to get. This is to protect the variables from accidentally being changed. In the real world of programming, a program may have many hundreds or thousands of functions, and teams of programmers working on the same program. There would be a good chance for variables to have the same name and a great mix up could occur resulting in constant errors. Consider the following:



int main()

{

   

    {

        int x = 0;

    }



    int x = 7;



}



Those two x's are separate variables with separate addresses. The first x only exists within the braces in which it was created, and ceases to exist outside of those braces. The second x exists and is accessible anywhere in main() (i.e. within the braces of main). When program execution enters the braces of the first x, that x is created and that x has priority since that is the current context (or scope). Just like neighboring cities, both can have a street called "Main street" and there is no confusion. Each Main street is in it's own scope. If you tell your friend that you are on Main street then she will assume you mean the one in your city since that is the current context. Think of the braces { } as separate little cities, and these cities can be nested in other cities in your program. This way a variable named x in main() is separate from a variable named x in a function called foo. So if there are many programmers working on the same huge program, and many hundreds of functions are being written, no one has to worry about the names of their variables clashing with other names in other functions written by other programmers. The software for the F-35 fighter jet is written in C++. There are something like 24 million lines of code and over 120 software engineers working on it. The fact that variables are playing "hard to get" and are not accessible outside of the braces in which they were created makes life much easier when writing large programs. A little extra effort (pointers) are required to get at variables outside their normal scope, which make accidents less likely to happen, and actually makes programming easier in the long run.



Of course, the processor (CPU) is fully capable of directly addressing all of the memory so it could reach any variable anywhere, even as far away as other programs that may be running at the same time. But the compiler restricts that with the rules of variable scope (within the braces { } darling). These are called local variables and they are local to the function. In reality, the compiler is just enforcing the rules of the C language standard.



"< Why must we assign a new variable to the address of another variable instead of use the address directly>"



We do use the address of a variable directly all the time. Whenever we use the name of a variable, like x + 1, then we are using the address of that variable directly (well, the address is represented as an easily remembered name instead of a long numerical address). The name of a variable is it's address. If we say, "x + 1" then the compiler looks up x in it's listing and finds that it's address is 0xb80ff and thus writes [0xb80ff] + 1.



But as just explained, the compiler won't allow us to use the address directly for variables that are far away (out of scope) so we need to reach them indirectly with a pointer. So if there was a variable x in main() and we were about to leave main() for the function foo, then we would need to create a pointer in main() and assign it the address of x. Then we would pass the pointer to foo. From within foo we could use the pointer, which is like the long arm of the law, which can reach far beyond state lines, to change the actual value in x back in main(). In fact, the pointer has such a long arm that it can reach anywhere in the computer's entire RAM memory, and the compiler won't even say anything if we do. However, if your program did have a pointer that pointed way outside your own program area then the Windows operating system would take action. Windows carefully watches the execution of your program, and if a bad pointer ends up trying to mess with anything outside of your program space Windows will quickly shut down your program and give a message like, "Sorry, but your program has encountered an error and needs to close". If you ever get that message, suspect a bad pointer value, like running past the end of an array for example and ending up trespassing in "unauthorized" areas.



""



What do you mean by "class"? In Object Orientated programming, the variables in the class can be accessed if they have public access, but not so if they were declared private. But with a function, how would you ever be outside the function? If a function isn't running then it isn't in existence. Think of a function this way: When it is called, it and all of it's variables pop into existence, it performs all of it's calculations and then it and all of it's variables vanish without a trace, leaving just some swirling dust where it once stood. So a function pops up and is here for just a brief moment and then is gone. So how can you be outside of a function when it wouldn't even exist? Any answer or result that was calculated would have to be passed out of the function to be caught by a waiting variable back in main() (like x = foo(); ) before the function and all of it's variables wink out of existence. But actually, the variables that were in the function that ended are probably still in their respective memory locations and haven't been overwritten yet, as they are declared to be free memory. So you could conceivably make a pointer in your foo() function and load it with the address of a variable there and then return the pointer to main(). Then when the function ends and disappears, you could use this pointer to see if the variable was still in it's grave and in good shape. It MIGHT be if it wasn't overwritten yet. Of course this is very unacceptable practice and really isn't necessary.



One more thing about being outside of a function. Actually you can be, like if foo() called a function itself, say foo2(). When foo2() was executing then foo() would still be around but in a paused state as foo2() did it's thing (this is always the case with the main() function when it calls a function, since the end of main() is the end of the whole program). So when foo2() was done it and all of it's variables would vanish and control would return to foo() and then foo() would finish and end and it and all of it's variables would vanish as control returned to main().
Grumpy Mac
2017-03-13 04:37:48 UTC
If you malloc some memory to hold a bunch of data, say a name, you get a variable pointing to the beginning of the address.



You can write data into that address, but you then often need to bump the pointer to end of the data to add more data. If you do this - how do you ever get back to the beginning?



So you often keep the variable that points to the beginning of the memory. Then create a separate variable to move through the memory.



"2. I am especially wondering why the variable that designed inside of a function(class) cannot be accessed outside of the class?"



"C" does not have classes so your question is almost a troll question.



Short Answer: Variables inside of functions are "Stack" variables. Global variables are in system memory.



When you "grab a global", the CPU has to take 6-10 clock cycles to put the address on the address-buss, wait for the memory controller to find the data, put the data on the data buss, then pull it into a CPU register so the code can do something with it. A global variable is also usually initialized to zero/null.



A local variable in a function is a "Stack" variable. The compiler looks at all the variables created in the function, bumps the stack pointer X bytes, Then makes the variables 'point' to places along the stack and ... that is it. A "Stack" variable is NOT initialized. The programmer must write code to set the initial values.



In many cases Stack memory is internal to the CPU. This makes reading/writing stack variables 3-10 times faster than global variables.



Stack variables are much faster than global's, but when the function exits, the stack pointer is moved back, the variables disappear and the memory is then given to the next function.





So local/Stack variables are much faster than memory variables, but they are temporary. It is up to the skills of the programmer to choose what type of memory to use for different variables.
no1home2day
2017-03-13 02:47:09 UTC
A pointer is a type of variable, but instead of holding data, it holds a memory address, and the memory address holds the data.



It's important because if you have a function that needs to modify a variable, if you send the variable with the data, the data cannot be changed, but if you send a pointer into the function, the function has access to the actual memory location, and can then change the value of the data.



That's why we use the ADDRESS of the variable, rather than the variable itself.



As far as a variable within a function or class, that is called "scope". The scope of a variable refers to the portion of the program that can actually refer to that variable, and the variable stops existing (for lack of a better way of describing it) when an "end" or "}", or some other close statement (depending on the language).



So, specifically in C, if you declare a variable at the beginning "{" of a function, once the program reaches the matching "}", the variable will no longer exist. You can even put a block "{ code }" in the middle of a function, and declare a variable within that block of code, and that variable will only exist (i.e. the SCOPE of that variable) until the program reaches the "}" (or END of block).


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...