Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

c - Using a struct vs a pointer to a struct

I was working on the following as an example to see the differences between passing an object directly and then passing a pointer to it:

#include "stdio.h"

// Car object
typedef struct Car {
    char*           name;
    unsigned int    price;
} Car;

void print_car(Car car) {
    printf("<Car: %s, Price: $%d>", car.name, car.price);
};

void print_car2(Car *car) {
    printf("<Car: %s, Price: $%d>", car->name, car->price);
};

int main(int argc, char* argv[]) {

    Car chevy = {chevy.name = "Chevy", chevy.price = 45000};
    print_car(chevy);

    Car mazda = {chevy.name = "Mazda", chevy.price = 30000};
    print_car2(&mazda);

    return 1;

}

Other than the first approach being much more readable and easier to understand for me, what are the differences between the two? When would passing a pointer be the only option, and why do both work in the above case?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In general (not only for structs) passing a variable to a function will make a copy of this variable so if you want to alter this variable you ll have to return the value of the altered copy but you may want to alter the variable and return something else, in this case you have no other choice of passing a pointer as argument exemple :

first exemple with passing a variable

int useless_func(int nb) /*nb is actually a copy of the variable passed as argument */
{
    nb++; /* the copy was incremented, not the real variable */
    return nb; /* the new value is returned */
}
int main()
{
    int nb = 1;

    useless_func(nb); /* here nb is still = 1 cause it wasn't altered by the function */
    nb = useless_func(nb); /* here nb is = 2 cause it took the return value of the func */
}

now a second stupid exemple with pointer :

char *useless_func(int *nb) /* nb is now a pointer to the variable */
{
    *nb++; /* the derefencement of the pointer (so the variable value) was incremented */
    return strdup("This is a useless return"); /* we return some other stupid stuff */
}
int main()
{
    int nb = 1;
    char *str = useless_func(&nb); /* now nb is = 2 and str is an allocated useless string woohoo */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...