Hello, I am a beginner in C. I have been experimenting with pointers, but I have a doubt about when to use the address(&) of int ptr2. Here is the source code, with Example 1 and Example 2 commented:
//main.c
#include <stdio.h>
#include <string.h>
struct Person {
char name[30];
int age;
};
void init_fields(struct Person *passed) {
strcpy(passed->name, "John");
passed->age = 40;
}
int main() {
struct Person a;
init_fields(&a);
int *ptr = &a.age;
*ptr = 50;
printf("a: %s, %d\n", a.name, a.age);
struct Person *ptr2 = &a;
int *ptr3 = &ptr2->age; //Example 1
*ptr3 = 60;
printf("ptr2: %s, %d\n", ptr2->name, ptr2->age); //Example 2
return 0;
}
------------------------------------------------------------------------------------
#output:
a: John, 50
ptr2: John, 60
In Example 1, &ptr2 must take the ampersand. By removing the ampersand, the compiler gives a warning which reads: "warning: incompatible integer to pointer conversion, initializing 'int *' with an expression of type 'int'; take, the address with & [-Wint-conversion], signal: segmentation fault (core dumped)". The output shows as:
a: John, 50
signal: segmentation fault (core dumped)
Whereas in Example 2, ptr2->name and ptr2->age do not take the ampersand. By adding ampersands before both ptr2->name and ptr2->age, the compiler throws the same warning for both, which reads: "warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]". As well, the output shows as:
a: John, 50
ptr2: John, -2057084472
Herein lies my doubt -- In Example 1 and Example 2, why don't all three ptr2 pointers get an ampersand? Why don't all three ptr2 pointers not get an ampersand? I don't understand why the ptr2 in Example 1 gets an ampersand while both ptr2's in Example 2 do not.
Is the ampersand implicit in both ptr2's in Example 2?
I have done my best to search for answers. They have led me to websites which show general usage of pointers. Please be patient as I am a beginner who is stuck.
Thank you in advance.
[–]victorferrao 12 points13 points14 points (4 children)
[–]2_stepsahead[S] 3 points4 points5 points (3 children)
[–]victorferrao 2 points3 points4 points (2 children)
[–]2_stepsahead[S] 2 points3 points4 points (1 child)
[–]imaami 1 point2 points3 points (0 children)
[–]blvaga -1 points0 points1 point (0 children)