C Question

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

Answer

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.

Comments