问题
Me and my friend is using structs in our code (our code is separate from each other). Lets take the following example:
struct Book {
char title;
int pages;
}
void setBook(struct Book *tempBook) {
tempBook->title = "NiceTitle";
tempBook->pages = 50;
}
The above code is pretty straight forward. The thing is, is there any difference in having these two mains:
int main() {
struct book obj1;
setBook(&obj);
}
Or
int main() {
struct Book *obj2;
setBook(obj2);
}
EDIT: I was not clear in my statement. I have initialized the pinter to
struct Book *obj2 = malloc(sizeof(struct obj2));
回答1:
In case of
struct book obj1;
setBook(&obj);
you're passing a valid address#1 to the function, so the behaviour is defined.
On the other hand,
struct Book *obj2;
setBook(obj2);
you're passing an unitialized pointer#2, accessing which invokes undefined behavior.
That said, the member char title;
should be char *title;
, as the string literal, when used as initializer, decays to the pointer to the first element, so you'll need a pointer on the LHS.
#1 -- obj1
is an automatic local variable, and address of that variable is a valid address in the scope.
#2 -- struct Book *obj2;
defines a pointer and again, obj2
being an automatic local variable, it is not implicitly initialized to anything. So, the initial value (i.e., the memory address at which the pointer points) is indeterminate and pretty well invalid.
回答2:
struct Book *obj2;
in main
is just a pointer with an indeterminate value. It doesn't point to anything you allocated. You can dereference it, but that's undefined behavior.
struct Book obj1;
allocates a struct Book
. You can use its address and modify its members.
Notes:
title
fromstruct Book
is achar
, which can only hold one character, not a string (i.e., a pointer). Usechar *
orconst char *
instead.
回答3:
In the first case you are passing a variable of type 'struct Book' to 'setBook function. Since you declared the variable hence total memory occupied by obj1 -s sizeof(setBook) i.e. sizeof(char)+sizeof(int) which is equal to 5 bytes. hence you can access as obj1 .title(1 byte) and obj1.pages(4 bytes).
NOTE:- Assuming int is 4 byte long.
Let's see what happen in second scenario.
struct Book *obj2; obj2 size id 4 bytes since it is a general pointer.The field is not divided either and hence we cannot access the field.
Hence, In second scenario, you need to allocate is dynamically before trying to use the members.The allocation will result in proper sized and properly divided field.
来源:https://stackoverflow.com/questions/40631631/using-pointers-or-references-to-struct