Reputation: 9
trying to remember the syntax for updating a pointer in a struct. I have something like this for example.
typedef struct {
char *name;
}car;
And I have a function which is called
void update_Name(car *d, char *newname)
{
car->name = &newname;
}
Is that correct or would it just be simply newname? Very straight forward dont worry about any other syntaxes or functions needed just wanted to know straight up how that would be updated. Thank you
Upvotes: 0
Views: 899
Reputation: 224457
First, car->name
is not correct because car
is the name of a type, not a variable. You want d->name
instead.
With that correction, the type of d->name
is char *
. You're attempting to assign an expression of type char **
to it which doesn't match.
newname
is already of type char *
which matches the type of d->name
, so you can assign it directly.
d->name = newname;
Upvotes: 0
Reputation: 54355
That is not quite correct.
You have a char *newname
function parameters. You have a char *name
struct member. &newname
creates a pointer to newname which would be char **
. Not what you want.
You just want car->name = newname;
That assigns a char*
to a char*
.
Always be sure to compile your programs with maximum warning levels. It will tell you when you assign mismatched pointers.
And also in code like this remember memory and pointer lifetimes. You are assigning a pointer to characters into a structure. Whatever that points to needs to survive at least as long as your car
structure or your car->name
will become a "dangling pointer" pointing to dead memory.
Upvotes: 2