I'm wondering what's the difference between sample1 and sample2. Why sometimes I have to pass the struct as an argument and sometimes I can do it without passing it in the function? and how would it be if samplex function needs several structs to work with? would you pass several structs as an argument?
struct x
{
int a;
int b;
char *c;
};
void sample1(struct x **z;){
printf(" first member is %d \n", z[0]->a);
}
void sample2(){
struct x **z;
printf(" first member is %d \n", z[0]->a); // seg fault
}
int main(void)
{
struct x **z;
sample1(z);
sample2();
return 0;
}
First of all, your argument type is not struct, but a pointer to pointer to struct (or an array of pointers to struct - these are semantically equivalent from the callee's point of view, except that the address of an array can't be changed).
In the second case you use a local variable that is totally independent of the one with same name in main. Since it is not initialized, you get a seg fault when trying to access one of its members. (The one in main is not initialized either, but accessing it just seems to work by chance in sample1).
You should initialize your variables before using them, otherwise you enter the territory of undefined behaviour. E.g.
void sample1(struct x **z){
printf(" first member is %d \n", z[0]->a);
}
void sample2(){
struct x z[1];
z[0].a = 1;
...
printf(" first member is %d \n", z[0].a);
}
int main(void)
{
struct x z[1];
z[0].a = 1;
...
sample1(z);
sample2();
return 0;
}
Both are invalid and accessing bad memory. The results are undefined so both results are correct.
C and C-like languages have a concept of "scope". See all those curly braces ({ and })? Those are "blocks". They essentially wrap all the code between them into bundles that are independent of any other blocks at the same level. Any variable you create in that block is only accessible within that block—you can't reference it anywhere else.
You can create a nested block. For example:
int f() {
int x;
scanf("%d", &x);
if (x == 3) {
return 7;
}
else {
return x;
}
}
As you can see, the else block is nested inside the function's block, and so can access the function's variables.
When you declare struct x **z in both main and sample2, you're actually creating two variables, both called z. These are totally independent—they're not the same variable at all. They're not related. The only thing they have in common is their name and type—the actual value is different. The only way you can use the same variable in both is by passing, as you do in sample1.
Of course, currently, your z pointer is garbage—you haven't allocated anything. I'd recommend you actually store something in there before you try and dereference it.
Your declaration
struct x **z;
simply creates a pointer to a pointer to a structure of type x. You're not actually initialising the pointers, i.e. making them point anywhere.
Try something like
struct x z;
struct x *pZ = &z;
sample1(&pZ);
(I'm not completely sure what you're actually trying to achieve, though!)
Related
I am trying to get deep acknowledge of pointers. while I am running this example it doesn't output any thing due to segmentation fault. But when I am trying to run the code line by line from GDB it works normally
Look at screen shot.
#include <stdio.h>
struct s{
int a;
struct s* next;
};
struct s foo() {
struct s m ;
struct s f[10];
m.a = 55;
m.next =&(f[0]);
int i = 0;
while(i < 9) {
f[i].a = 28 + i;
f[i].next = &(f[i+1]);
i++;
}
return f[0];
}
int main()
{
struct s f = (foo());
printf("%d ",f.a);
printf("%d ",f.next->a);
printf("%d ",f.next->next->a);
return 0;
}
if you change the main function to be like this :
int main(){
struct s f = (foo()); int a = f.a;
int b - f.next->a;
int c = f.next->next->a;
int d = f.next->next->next->a;
int g = f.next->next->next->next->a;
printf("%d %d %d %d %d\n", a, b , c ,d, g);
}
it will work fine.
this screen shot is n't working when I am trying to call printf directly .
this is working when I am trying to store in variables first and then call printf on the variables
]
In C, variables that are defined inside a function are either static or automatic (auto). The default is automatic. The lifetime of automatic variables ends when the function returns and its return value has been copied to another variable or used in an expression.
struct s foo() {
struct s f[10];
int i = 0;
while(i < 9) {
f[i].a = 28 + i;
f[i].next = &(f[i+1]);
i++;
}
return f[0];
}
int main()
{
struct s f = (foo())
So after foo's return value has been stored in main's f, foo's f array is no longer alive, and trying to access any part of it is an error.
So why does the following work?
int b = f.next->a;
int c = f.next->next->a;
int d = f.next->next->next->a;
int g = f.next->next->next->next->a;
printf("%d %d %d %d %d\n", a, b , c ,d, g);
The reason is that your implementation of C stores automatic variables in a stack, and doesn't shrink the stack after a function finishes. Instead, the variables remain undisturbed until another function is called. That function will reuse all or part of the stack space, overwriting variables without regard to their old types. A pointer may be overwritten by an integer, or a few character of a string, or something else.
So, although it's undefined behavior and you should never rely on this working, you can access parts of the f array in this particular case because no function has been called since foo returned.
Similarly, in your GDB session, since you've stopped your program after foo returns but before printf has been called, GDB can safely access f.next->next->a, etc., but it's still undefined behavior.
Your second version does call functions, and that's when you're going to run into trouble.
printf("%d ",f.a);
printf("%d ",f.next->a);
printf("%d ",f.next->next->a);
The first line, printf("%d ",f.a), will work fine. main's f is valid. But the call to printf is going to overwrite the stack previously used by foo, including all or part of what used to be foo's f array.
Note that you won't see this output yet, because printf won't print out anything until you've asked it to print the end-of-line character.
The next line, printf("%d ",f.next->a);, is going to print a seemingly random integer, because foo's f[1].a has been overwritten with whatever local variables printf uses. And, again, you won't see any output yet because of buffering.
The next line, printf("%d ",f.next->next->a), is where things come crashing down. foo's f[1].next is almost certainly not going to be a valid pointer, so you get a segmentation fault.
How can you make this work correctly? If you want foo's f array to stay alive for the entire duration of the program, just prefix the declaration with the keyword static. That means there will be one copy of the f array, no matter how many times you call foo. If you want each call to foo to allocate a new f array, you can use the malloc function. Space allocated by malloc will remain alive until either you call free or the program exits.
#include <stdio.h>
typedef struct
{
int a;
int b;
}my_struct;
void check (my_struct *my_check)
{
printf ("%d\n", my_check->a);
}
int main()
{
//block with local variables
{
int a = 2;
printf("int inside block %d\n", a);
my_struct m1;
m1.a = 2;
printf ("my_struct m1 inside block\t");
check (&m1);
}
//outside the block; so the variables and their values inside the above block is outside the scope of the following code
int a;
printf("int outside block %d\n", a);
my_struct m2;
my_struct m1;
printf ("my_struct m1 outside block\t");
check (&m1);
printf ("my_struct m2 outside block\t");
check(&m2);
return 0;
}
The above piece of code will output
int inside block 2
my_struct m1 inside block 2
int outside block 0
my_struct m1 outside block 2
my_struct m2 outside block 522062864
My question is:
Why "int a" inside the block was not accessible with a variable of same name i.e. int a, but "my_struct m1" was?
My understanding is, if it is outside the block, then it is fresh declaration and definition. New assignment is needed for variables outside, else they will contain default/garbage values
You are in the world of Undefined Behaviour. You have created some variables in the inside block. Fine. Then when you exit the block, those variables vanish. You now create different variables in the outside. And you try to use those uninitialized variables which is explicitely Undefined Behaviour.
That means that what happens could be different from one system to another one, or on the same system with different compilation options, or even on different runs. And anyway, you should never rely on that consistently happening.
Now what actually happens in that system and in that specific run: your implementation probably uses the stack for the structures and registers for single values for which you never use an address. So when you create a new single variable it receives what was in a register and could be anything. But when you create a new struct it just reuses the memory that has just be released by the previous one, and you get the old value. But as I have already said you cannot rely on that.
I've just started to work with C, and never had to deal with pointers in previous languages I used, so I was wondering what method is better if just modifying a string.
pointerstring vs normal.
Also if you want to provide more information about when to use pointers that would be great. I was shocked when I found out that the function "normal" would even modify the string passed, and update in the main function without a return value.
#include <stdio.h>
void pointerstring(char *s);
void normal(char s[]);
int main() {
char string[20];
pointerstring(string);
printf("\nPointer: %s\n",string);
normal(string);
printf("Normal: %s\n",string);
}
void pointerstring(char *s) {
sprintf(s,"Hello");
}
void normal(char s[]) {
sprintf(s,"World");
}
Output:
Pointer: Hello
Normal: World
In a function declaration, char [] and char * are equivalent. Function parameters with outer-level array type are transformed to the equivalent pointer type; this affects calling code and the function body itself.
Because of this, it's better to use the char * syntax as otherwise you could be confused and attempt e.g. to take the sizeof of an outer-level fixed-length array type parameter:
void foo(char s[10]) {
printf("%z\n", sizeof(s)); // prints 4 (or 8), not 10
}
When you pass a parameter declared as a pointer to a function (and the pointer parameter is not declared const), you are explicitly giving the function permission to modify the object or array the pointer points to.
One of the problems in C is that arrays are second-class citizens. In almost all useful circumstances, among them when passing them to a function, arrays decay to pointers (thereby losing their size information).
Therefore, it makes no difference whether you take an array as T* arg or T arg[] — the latter is a mere synonym for the former. Both are pointers to the first character of the string variable defined in main(), so both have access to the original data and can modify it.
Note: C always passes arguments per copy. This is also true in this case. However, when you pass a pointer (or an array decaying to a pointer), what is copied is the address, so that the object referred to is accessible through two different copies of its address.
With pointer Vs Without pointer
1) We can directly pass a local variable reference(address) to the new function to process and update the values, instead of sending the values to the function and returning the values from the function.
With pointers
...
int a = 10;
func(&a);
...
void func(int *x);
{
//do something with the value *x(10)
*x = 5;
}
Without pointers
...
int a = 10;
a = func(a);
...
int func(int x);
{
//do something with the value x(10)
x = 5;
return x;
}
2) Global or static variable has life time scope and local variable has scope only to a function. If we want to create a user defined scope variable means pointer is requried. That means if we want to create a variable which should have scope in some n number of functions means, create a dynamic memory for that variable in first function and pass it to all the function, finally free the memory in nth function.
3) If we want to keep member function also in sturucture along with member variables then we can go for function pointers.
struct data;
struct data
{
int no1, no2, ans;
void (*pfAdd)(struct data*);
void (*pfSub)(struct data*);
void (*pfMul)(struct data*);
void (*pfDiv)(struct data*);
};
void add(struct data* x)
{
x.ans = x.no1, x.no2;
}
...
struct data a;
a.no1 = 10;
a.no1 = 5;
a.pfAdd = add;
...
a.pfAdd(&a);
printf("Addition is %d\n", a.ans);
...
4) Consider a structure data which size s is very big. If we want to send a variable of this structure to another function better to send as reference. Because this will reduce the activation record(in stack) size created for the new function.
With Pointers - It will requires only 4bytes (in 32 bit m/c) or 8 bytes (in 64 bit m/c) in activation record(in stack) of function func
...
struct data a;
func(&a);
...
Without Pointers - It will requires s bytes in activation record(in stack) of function func. Conside the s is sizeof(struct data) which is very big value.
...
struct data a;
func(a);
...
5) We can change a value of a constant variable with pointers.
...
const int a = 10;
int *p = NULL;
p = (int *)&a;
*p = 5;
printf("%d", a); //This will print 5
...
in addition to the other answers, my comment about "string"-manipulating functions (string = zero terminated char array): always return the string parameter as a return value.
So you can use the function procedural or functional, like in printf("Dear %s, ", normal(buf));
Title pretty much sums this up. How come it's possible that i can assign a locally created Point a (in the function ReadPoint()) into a variable that's in a different scope. Doesn't the locally created Point a gets 'popped' away along with stack of function readPoint() ? What exactly is going on ?
struct Point readPoint(void)
{
struct Point a;
printf("x = ");
scanf("%lf",&b.x);
printf("y = ");
scanf("%lf",&b.y);
return a;
}
int main(int argc, char **argv) {
Point test = readPoint();
printPoint(test);
return 0
}
structs are no different to primitive types in this regard. It's exactly the same principle as:
int foo(void)
{
int x = 5;
return x;
}
int main(void)
{
int y = foo();
printf("%d\n", y);
}
The details of how this is achieved are implementation-dependent. But usually, the return value (whether it's an int or a struct) is placed onto the stack by the called function, and then the caller then can then access that stack location.
The struct is "copied", byte by byte, into test in main...just like returning an int from a function and assigning it to a variable.
This, however, wouldn't happen if you were returning a pointer to the struct and the dereferencing it and assigning (or something similar).
When returning, you'll create a copy of the object (with all members of the struct), but the local variable/object is still destroyed.
This will work unless you try to return a reference or pointer (in these cases your compiler should warn you about this stupid idea). This will work fine, unless you're trying to create a copy of something working with pointers.
In C++ this would include references too.
This is because on return from readPoint() all structure values are copied to another locally defined structure test. Structure a does not survive.
What you're seeing is structure assignment. Almost all modern compilers can handle this.
This is a very simple question but what does the following function prototype mean?
int square( int y, size_t* x )
what dose the size_t* mean? I know size_t is a data type (int >=0). But how do I read the * attached to it? Is it a pointer to the memory location for x? In general I'm having trouble with this stuff, and if anybody could provide a handy reference, I'd appreciate it.
Thanks everybody. I understand what a pointer is, but I guess I have a hard hard time understanding the relationship between pointers and functions. When I see a function prototype defined as int sq(int x, int y), then it is perfectly clear to me what is going on. However, when I see something like int sq( int x, int* y), then I cannot--for the life of me--understand what the second parameter really means. On some level I understand it means "passing a pointer" but I don't understand things well enough to manipulate it on my own.
How about a tutorial on understanding pointers?
In this case however, the pointer is probably used to modify/return the value. In C, there are two basic mechanisms in which a function can return a value (please forgive the dumb example):
It can return the value directly:
float square_root( float x )
{
if ( x >= 0 )
return sqrt( x );
return 0;
}
Or it can return by a pointer:
int square_root( float x, float* result )
{
if ( x >= 0 )
{
*result = sqrt( result );
return 1;
}
return 0;
}
The first one is called:
float a = square_root( 12.0 );
... while the latter:
float b;
square_root( 12.00, &b );
Note that the latter example will also allow you to check whether the value returned was real -- this mechanism is widely used in C libraries, where the return value of a function usually denotes success (or the lack of it) while the values themselves are returned via parameters.
Hence with the latter you could write:
float sqresult;
if ( !square_root( myvar, &sqresult ) )
{
// signal error
}
else
{
// value is good, continue using sqresult!
}
*x means that x is a pointer to a memory location of type size_t.
You can set the location with x = &y;
or set the value were x points to with: *x = 0;
If you need further information take a look at: Pointers
The prototype means that the function takes one integer arg and one arg which is a pointer to a size_t type. size_t is a type defined in a header file, usually to be an unsigned int, but the reason for not just using "unsigned int* x" is to give compiler writers flexibility to use something else.
A pointer is a value that holds a memory address. If I write
int x = 42;
then the compiler will allocate 4 bytes in memory and remember the location any time I use x. If I want to pass that location explicitly, I can create a pointer and assign to it the address of x:
int* ptr = &x;
Now I can pass around ptr to functions that expect a int* for an argument, and I can use ptr by dereferencing:
cout << *ptr + 1;
will print out 43.
There are a number of reasons you might want to use pointers instead of values. 1) you avoid copy-constructing structs and classes when you pass to a function 2) you can have more than one handle to a variable 3) it is the only way to manipulate variables on the heap 4) you can use them to pass results out of a function by writing to the location pointed to by an arg
Pointer Basics
Pointers And Memory
In response to your last comment, I'll try and explain.
You know that variables hold a value, and the type of the variable tells you what kind of values it can hold. So an int type variable can hold an integer number that falls within a certain range. If I declare a function like:
int sq(int x);
...then that means that the sq function needs you to supply a value which is an integer number, and it will return a value that is also an integer number.
If a variable is declared with a pointer type, it means that the value of that variable itself is "the location of another variable". So an int * type variable can hold as its value, "the location of another variable, and that other variable has int type". Then we can extend that to functions:
int sqp(int * x);
That means that the sqp function needs to you to supply a value which is itself the location of an int type variable. That means I could call it like so:
int p;
int q;
p = sqp(&q);
(&q just means "give me the location of q, not its value"). Within sqp, I could use that pointer like this:
int sqp(int * x)
{
*x = 10;
return 20;
}
(*x means "act on the variable at the location given by x, not x itself").
size_t *x means you are passing a pointer to a size_t 'instance'.
There are a couple of reasons you want to pass a pointer.
So that the function can modify the caller's variable. C uses pass-by-value so that modifying a parameter inside a function does not modify the original variable.
For performance reasons. If a parameter is a structure, pass-by-value means you have to copy the struct. If the struct is big enough this could cause a performance hit.
There's a further interpretation given this is a parameter to a function.
When you use pointers (something*) in a function's argument and you pass a variable you are not passing a value, you are passing a reference (a "pointer") to a value. Any changes made to the variable inside the function are done to the variable to which it refers, i.e. the variable outside the function.
You still have to pass the correct type - there are two ways to do this; either use a pointer in the calling routine or use the & (addressof) operator.
I've just written this quickly to demonstrate:
#include <stdio.h>
void add(int one, int* two)
{
*two += one;
}
int main()
{
int x = 5;
int y = 7;
add(x,&y);
printf("%d %d\n", x, y);
return 0;
}
This is how things like scanf work.
int square( int y, size_t* x );
This declares a function that takes two arguments - an integer, and a pointer to unsigned (probably large) integer, and returns an integer.
size_t is unsigned integer type (usually a typedef) returned by sizeof() operator.
* (star) signals pointer type (e.g. int* ptr; makes ptr to be pointer to integer) when used in declarations (and casts), or dereference of a pointer when used at lvalue or rvalue (*ptr = 10; assigns ten to memory pointed to by ptr). It's just our luck that the same symbol is used for multiplication (Pascal, for example, uses ^ for pointers).
At the point of function declaration the names of the parameters (x and y here) don't really matter. You can define your function with different parameter names in the .c file. The caller of the function is only interested in the types and number of function parameters, and the return type.
When you define the function, the parameters now name local variables, whose values are assigned by the caller.
Pointer function parameters are used when passing objects by reference or as output parameters where you pass in a pointer to location where the function stores output value.
C is beautiful and simple language :)
U said that u know what int sq(int x, int y) is.It means we are passing two variables x,y as aguements to the function sq.Say sq function is called from main() function as in
main()
{
/*some code*/
x=sr(a,b);
/*some other code*/
}
int sq(int x,int y)
{
/*code*/
}
any operations done on x,y in sq function does not effect the values a,b
while in
main()
{
/*some code*/
x=sq(a,&b);
/*some other code*/
}
int sq(int x,int* y)
{
/*code*/
}
the operations done on y will modify the value of b,because we are referring to b
so, if you want to modify original values, use pointers.
If you want to use those values, then no need of using pointers.
most of the explanation above is quite well explained. I would like to add the application point of view of this kind of argument passing.
1) when a function has to return more than one value it cannot be done by using more than one return type(trivial, and we all know that).In order to achieve that passing pointers to the function as arguments will provide a way to reflect the changes made inside the function being called(eg:sqrt) in the calling function(eg:main)
Eg: silly but gives you a scenario
//a function is used to get two random numbers into x,y in the main function
int main()
{
int x,y;
generate_rand(&x,&y);
//now x,y contain random values generated by the function
}
void generate_rand(int *x,int *y)
{
*x=rand()%100;
*y=rand()%100;
}
2)when passing an object(a class' object or a structure etc) is a costly process (i.e if the size is too huge then memory n other constraints etc)
eg: instead of passing a structure to a function as an argument, the pointer could be handy as the pointer can be used to access the structure but also saves memory as you are not storing the structure in the temporary location(or stack)
just a couple of examples.. hope it helps..
2 years on and still no answer accepted? Alright, I'll try and explain it...
Let's take the two functions you've mentioned in your question:
int sq_A(int x, int y)
You know this - it's a function called sq_A which takes two int parameters. Easy.
int sq_B(int x, int* y)
This is a function called sq_B which takes two parameters:
Parameter 1 is an int
Parameter 2 is a pointer. This is a pointer that points to an int
So, when we call sq_B(), we need to pass a pointer as the second
parameter. We can't just pass any pointer though - it must be a pointer to an int type.
For example:
int sq_B(int x, int* y) {
/* do something with x and y and return a value */
}
int main() {
int t = 6;
int u = 24;
int result;
result = sq_B(t, &u);
return 0;
}
In main(), variable u is an int. To obtain a pointer to u, we
use the & operator - &u. This means "address of u", and is a
pointer.
Because u is an int, &u is a pointer to an int (or int *), which is the type specified by parameter 2 of sq_B().
Any questions?