简体   繁体   中英

Using pointers or references to struct

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));

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 (ie, the memory address at which the pointer points) is indeterminate and pretty well invalid .

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 from struct Book is a char , which can only hold one character, not a string (ie, a pointer). Use char * or const char * instead.

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) ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM