Why are pointers such a big deal in C? - c

I understand the premise of pointers, but I find it very annoying, and I don't get why it's considered useful;
I've learned about pointers, and the next thing I know, I start seeing bubbles, asterisks, and ampersands everywhere.
#include <stdio.h>
int main () {
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
}
why is this important or useful?

First, parameters passed to a function can only be primitives(int, char, long....), structs or pointers. Then if you need to pass a more complex element like an array (strings) or a function, you have to pass a reference to this element.
The second things that I can quickly think of is: parameters are always passed by "value". This means the called function only get a copy of your variable. So, modifications will only affect the copy, the original variable will remain unchanged.
If you pass a variable by "reference" with a pointer, the pointer itself is immutable but as it is a reference to the original var, any modification to the pointed element will also affect the var in the caller function.
In other words, if you want to create a function that can alter a variable, you have to pass it a pointer to that variable to achieve this.

Related

Does sprintf() modify variable across function?

I use sprintf() to fill my string, but when I'm not done, I found something strange, the var which names test can be modified even it is a argument, I thought it was just like a Rvalue when calling function, or here is somewhere I didn't notice, and the following is my code and output.
Thanks.
#include <stdio.h>
#include <stdlib.h>
void Encap(char str[9])
{
printf("%s\n", str);
sprintf(str, "hi e");
printf("%s\n%p\n", str, &str);
}
int main()
{
char test[9] = "ABC";
printf("%s\n", test);
Encap(test);
printf("%s\n%p\n", test, &test);
system("pause");
return 0;
}
Output
ABC
ABC
hi e
0061FF10
hi e
0061FF27
You declare an array test, and you pass it to the function Encap. Your question is a little unclear, but there are two things which may be surprising you:
Within the function Encap, you are modifying the contents of the array.
After the function Encap returns, back in the caller, the modifications to the test array persist.
(You also asked about "rvalue", which can be an important concept, but it doesn't apply here in the way that you expect.)
The reason this works the way it does is because of two different things:
When you pass the array test to the function Encap, you do not pass the entire value of the array. what actually gets passed is just a pointer to the array;s first element.
Within the function Encap, you are not modifying the pointer that was passed, instead, you are modifying the memory that the pointer points to. You are using the pointer as a value (a pointer value) to know where the memory is that you should modify -- and this ends up being the test array up in main().
You are passing pointer to function, It will surely change value at the memory location.
As you are passing pointer, another copy of pointer will be created and which will be used in function.(Whenever we call to a function, copy of variable is made and operations are done on that copy variable). Here the variable is of type pointer, hence another pointer variable will be created which will be pointing to same memory locations as pointed by test but will be having different address.
That's why two different memory address gets printed as you are printing address of two different pointers.

What is C-equivalent of reference to a pointer "*&"

Could someone please let me know the C-equivalent of reference to a pointer "*&"?
In other word, if my function is like this in C++:
void func(int* p, int*& pr)
{
p++;
pr++;
}
How would I changed the second argument while converting it in C?
UPDATE:
#MikeDeSimone : Please let me know if I understood the translated code properly?
Let me start by initializing variable:
int i = 10;
int *p1 = &i;
int **pr= &p1;
So, when you performed (*pr)++ , that is basically equivalent to:
(p1)++
However, I fail to understand how would that look from inside main()?
Question 2: what would I do if I have code snippet like this?
void pass_by_reference(int*& p)
{
//Allocate new memory in p: this change would reflect in main
p = new int;
}
You use a pointer to a pointer.
void func(int* p, int** pr)
{
p++;
(*pr)++;
}
See, for example, the second parameter to strtoul, which the function uses to return the point at which parsing stopped.
Sorry for the late update...
Please let me know if I understood the translated code properly? Let me start by initializing variable:
int i = 10;
int *p1 = &i;
int **pr= &p1;
So, when you performed (*pr)++ , that is basically equivalent to:
(p1)++
Yes.
However, I fail to understand how would that look from inside main()?
I don't understand how main comes into this; we were talking about func. For this discussion, main would be a function like any other. Variables declared within a function only exist during execution of that function.
Question 2: what would I do if I have code snippet like this?
void pass_by_reference(int*& p)
{
//Allocate new memory in p: this change would reflect in main
p = new int;
}
The thing to remember about references passed into functions is that they are just saying "this parameter is a reference to the parameter passed to the function, and changing it changes the original. It is not a local copy like non-reference parameters."
Reviewing references in practice:
If your function is declared void func(int foo); and called with int k = 0; foo(k); then a copy of k is made that func sees as foo.
If func changes foo, k does not change. You will often see functions "trash" their passed-in-by-copy parameters like this.
If your function is declared void func(int& foo); and called with int k = 0; foo(k); then a reference to k is made that func sees as foo.
If func changes foo, it is actually changing k.
This is often done to "pass back" more values than just the return value, or when the function needs to persistently modify the object somehow.
Now the thing is that C doesn't have references. But, to be honest, C++ references are C pointers under the hood. The difference is that references cannot be NULL, should not be taken as pointing to the start of a C array, and references hide the pointer operations to make it look like you're working on the variable directly.
So every time you see a reference in C++, you need to convert it to a pointer in C. The referred-to type does not matter; even if it's a pointer, the reference turns into a pointer itself, so you have a pointer-to-pointer.
So what's a pointer, anyway? Remember that memory is just a big array of bytes, with every byte having an address. A pointer is a variable that contains an address. C and C++ give pointers types so the language can determine what kind of data the pointer is pointing to. Thus an int is an integer value, and an int* is a pointer to an integer value (as opposed to a pointer to a character, or structure, or whatever).
This means you can do two general things with a pointer: you can operate on the pointer itself, or you can operate on the object the pointer is pointing to. The latter is what happens when you use unary prefix * (e.g. *pr) or -> if the pointer points to a structure. (a->b is really just shorthand for (*a).b.)

parameter passing in C function

I have a function written in C
FindBeginKey(KeyListTraverser, BeginPage, BeginKey, key1);
BeginKey is a pointer before function invoking, and I didn't initiate it, like
BeginKey = NULL;
In the FindBeginKey() function, I assign BeginKey to another pointer, and try to print out the current address of BeginKey in the function, it works correct.
But when code returns from function, I try to print out the address of BeginKey again, it shows 0x0.
Why does this happen, and if I want to preserve the address assigned in the function, what should I do?
To pass a value out of a function you have to pass by reference rather than by value as is normally the case with C functions. TO do this make the parameter a pointer to the type you want to pass out. Then pass the value into the call with the & (address operand).
e.g.
FindFoo(FOO** BeginKey);
and call it:
FindFoo(&BeginKey);
and in the function:
*BeginKey = 0xDEADC0DE;
From what I understand, you are calling the function like:
FindBeginKey(KeyListTraverser, BeginPage, BeginKey, key1);
However, when you try to write at the BeginKey address, you're basically passing in a pointer to 0x00. Rather, you need to pass a pointer to BeginKey.
FindBeginKey(KeyListTraverser, BeginPage, &BeginKey, key1);
If this is isn't what you meant, it would certainly help if you posted a code sample.
If you want to modify a parameter in a subroutine, you should pass a pointer of the thing you wanna modify.
void subroutine(int* x) {
*x = 5; // will modify the variable which x points to
x = 5; // INVALID! x is a pointer, not an integer
}
I don't know what all the C parameter passing rules are now, so this answer might be a little dated. From common practice in building applications and libraries that those applications called, the return from a C function would contain status, so the caller of the function could make a decision depending on the status code.
If you wanted the function to modify its input parameters, you would pass those parameters by reference &my_val, where int my_val;. And your function must dereference my_val like this *my_val to get its value.
Also, for performance reasons, and address (by reference) might be preferable, so that the your application did not bother copying the parameter's value into a local variable. That prolog code is generated by the compiler. Single parameters, char, int, and so on are fairly straight forward.
I am so used to C++ that passing by reference in C++ does not require dereferencing. The compiler's code takes care of that for you.
However, think about passing a pointer to a structure.
struct my_struct
{
int iType;
char szName[100];
} struct1;
struct my_struct *pStruct1 = &struct1;
If the structure contains lookup data that is filled in once on initialization and then referenced throughout your program, then pass a pointer to the structure by value pStruct1. If you are writing a function to fill that structure or alter already present data, then pass a pointer to the structure by value. You still get to alter what the structure pointer points to.
If on the other hand you are writing a function to assign memory to the pointer, then pass the address of the pointer (a pointer to the pointer) &pStruct1, so you will get your pointer pointing to the right memory.

Why would I pass function parameters by value in C?

I am dusting off my C skills working on some C libraries of mine. After having put together a first working implementation I am now going over the code to make it more efficient. Currently I am on the topic of passing function parameters by reference or value.
My question is, why would I ever pass any function parameter by value in C? The code might look cleaner, but wouldn't it always be less efficient than passing by reference?
Because it's not as important to code for the computer as it is to code for the next human being. If you are passing references around then any reader must assume that any called function could change the value of his parameters and would be obligated to check it or copy the parameter before calling.
Your function signature is a contract and divides your code up so that you don't have to fit the entire code base into your head in order to comprehend what is going on in some area, by passing references you are making the next guy's life worse, your biggest job as a programmer should be making the next guy's life better--because the next guy will probably be you.
In C, all arguments are passed by value. A true pass by reference is when you see the effect of a modification without any explicit indirection at all:
void f(int c, int *p) {
c++; // in C you can't change the original paramenter passed like this
p++; // or this
}
Using values instead of pointers though, is frequently desirable:
int sum(int a, int b) {
return a + b;
}
You would not write this like:
int sum(int *a, int *b) {
return *a + *b;
}
Because it is not safe and it is inefficient. Inefficient because there is an additional indirection. Moreover, in C, a pointer argument suggests the caller that the value will be modified through the pointer (especially true when the pointed type has a size less than or equal to the pointer itself).
Please refer to Passing by reference in C. Pass by reference is a misnomer in C. It refers to passing the address of a variable instead of the variable, but you are passing a pointer to the variable by value.
That said, if you were to pass the variable as a pointer, then yes it would be marginally more efficient, but the main reason is to be able to modify the original variable it points to. If you don't want to be able to do this, it is recommended you take it by value to make your intent clear.
Of course, all this is moot in terms of one of Cs heavier data structures. Arrays are passed by a pointer to their first variable whether you like it or not.
Two reasons:
Often times you will have to dereference the pointer you've passed in many times (think a long for-loop). You don't want to dereference every single time you want to look up the value at that address. Direct access is faster.
Sometimes you want to modify the passed-in value inside you function, but not in the caller. Example:
void foo( int count ){
while (count>0){
printf("%d\n",count);
count--;
}
}
If you wanted to do the above with something passed by reference, you would haev to create yet another variable inside your function to store it first.

C: Passing Struct to a Function doesn't result in a call by value operation

I have the following problem with a program which I wrote in Visual C++ and I hope that anyone can help me please:
typedef struct spielfeld
{
int ** Matrix;
int height;
int width;
Walker walker;
Verlauf history;
} Spielfeld;
void show(Spielfeld fieldToShow); //Prototype of the Function where I have this
//problem
int main(int argc, char *argv[])
{
int eingabe;
Spielfeld field;
//Initialize .. and so on
//Call show-Function and pass the structure with Call by Value
show(field);
//But what's happened? field.Matrix has changed!!
//can anyone tell me why? I don't want it to become changed!
//cause that's the reason why I pass the field as Call by Value!
}
void show(Spielfeld fieldToShow)
{
//Here is the problem: Alltough the parameter fieldToShow has been passed
//with call by value, "fieldToShow.Matrix[0][0] = 1" changes the field in
//main!!
fieldToShow.Matrix[0][0] = 1;
//Another try: fieldToShow.walker.letter only affects the local fieldToShow,
//not that field in main! That's strange for me! Please help!
fieldToShow.walker.letter = 'v';
}
When you pass the structure in, you are passing it in by value. However, the matrix within it is implemented as a pointer to pointer to int. Those pointers are references, and so when you modify the value referenced by them in your function, the same value is referenced by the original structure in main.
If you want to pass these objects by value, you need to do a deep copy yourself, in which you allocate a new matrix, and copy all of the values from the original matrix into it.
As Drew points out, in C++, the preferred way to implement that deep copy is via a copy constructor. A copy constructor allows you to perform your deep copy any time your object is passed by value, without having to explicitly copy the object yourself.
If you are not ready for classes and constructors yet, you can simply write a function, perhaps Spielfeld copySpielfeld(Spielfeld original), that will perform that deep copy; it will essentially be the same as your initialization code that you elided in your example, except it will take values from the Spielfeld passed in, instead of creating a new Spielfeld. You may call this before passing your field into the show function, or have the show function do it for any argument passed in, depending on how you want your API to work.
You're copying the pointer when you pass fieldToShow. Pass-by-value does not perform a deep copy, so both the Spielfeld in an invocation of show(...) and main(...) (although distinct) have the same value for Matrix.
Fixing this is non-trivial. Probably the easiest thing to do would be to change show(...) to pass-by-reference (using a Spielfeld* basically) and make an explicit copy at the start of the function.
When your Spielfeld object is copied:
The copy has its own "walker", which is a copy of the original's "walker". Since walker is a struct, that means you have two structs.
The copy has its own "Matrix" member, which is a copy of the original's "Matrix" member. But Matrix is a pointer, which means you have two pointers. A copy of a pointer points to the same thing the original points to.
So, modifications to the contents of the copy's walker don't affect the original, because they have different walkers. Modifications to the contents of the copy's matrix do affect the original, because they share the same matrix.
The structure is begin passed by value, but since it contains a pointer (the matrix) what that pointer is pointing to can be changed by anyone that has access to the structure. If you don't want this to happen, you can make the pointer const.
As interesting trivia: this is how call by value works in java. Object references are always passed by value. If you manipulate the objects to which these references point tough it will feel like call by reference happened.
Has really nothing to do with your question but maybe you find that interestring.
Happy hacking

Resources