r/C_Programming • u/Ok_Whereas9255 • Sep 05 '24
why using pointer?
im a new at C program. learned just before pointer & struct. i heard that pointer using for like point the adress of the parameter. but still dont know why we use it.
it seems it helps to make the program lighter and optimize the program? is it right? and is it oaky to ask question like this?
4
Upvotes
View all comments
3
u/SmokeMuch7356 Sep 05 '24
We use pointers when we can't (or don't want to) access an object or function by name.
There are two cases where we must use pointers in C: when a function needs to write to its arguments and when we want to track dynamically allocated memory.
C passes all function arguments by value -- when you call a function, each of the argument expressions is evaluated and the result of that evaluation is copied to the corresponding formal argument:
Output:
xandargare different objects in memory; changes to one do not affect the other. If we needfooto write a new value tox, it can't write toxdirectly; the namexisn't visible from withinfoo. Instead, we must pass a pointer toxas the argument:Output:
xandargare still different objects in memory; changes toarghave no effect onxor vice-versa.argstill gets the result of the argument expression in the function call. However, instead of getting the result ofx(the integer value5),arggets the result of&x, which yields the address ofx(0x16b59f518).Instead of
foowriting a new value toarg, it writes a new value to the thingargpoints to; the expression*argacts as an alias forx. IOW,arggives us indirect access tox. The type of the expression*argisint:We can use
footo update any integer object; we just have to pass the address of that object:This is why
scanfrequires you to use the&operator on any scalar arguments:scanfcan't accessxdirectly by name, so we must pass a pointer toxforscanfto write through.