Reputation:
I used pointer while printing structure elements but its working without using pointer in the print statement but shouldn't we use pointers to gather the element from the variable address why is it different in the structure case and its different in string also . Can anyone tell me why is that ?
#include <stdio.h>
int main(){
struct books{
char name[10];
int page;
};
struct books b1={"book1",1};
struct books *ptr;
ptr=&b1;
printf("%s %d",ptr->name,ptr->page);
}
Upvotes: 2
Views: 77
Reputation: 539
Pointers used when the object is too big and copying such object vastes time. But in your struct it takes 10 bytes for char array + 4 bytes for int and it's not a problem. In 64 bit machine pointers take 8 bytes in 32 bit 4 bytes. Suppose you have a big a struct and per object it takes 50 bytes of memory if you copy it will take more space and will be slower and by copying a brand new object will be created and that won't change anything in original one.
Let's see in practice when pointers can be used:
#include <stdio.h>
struct person{
char name[10];
int age;
};
void grow(struct person p) {
++p.age;
}
int main(){
struct person Mike = { "Mike", 20 };
grow(Mike);
printf("Name: %s\tAge: %d", Mike.name, Mike.age);
}
OUTPUT:
Name: Mike Age: 20
This code won't change age of Mike
because void grow(struct person p)
function copies struct person
by creating a new object then increments age and at the end destroys struct person p
. If you pass it as pointer then Mike
will be modified.
Upvotes: 1
Reputation: 9763
What MikeCAT said.
Beware though that an array would also be a pointer so *ptr->name
would compile but will produce the first character of 'name'.
struct books{
char name[10];
int page;
};
ptr=&b1;
printf("%c",*ptr->name);
Upvotes: 1
Reputation: 75062
printf("%s %d",*ptr->name,*ptr->page);
is wrong. A->B
means (*A).B
. You should do either
printf("%s %d",ptr->name,ptr->page);
or
printf("%s %d",(*ptr).name,(*ptr).page);
Upvotes: 3