+ 2
How to pass strings into structs (C) (SOLVED)
Hello, I want to create a function which takes a string variable and passes it into a struct. How would I be able to do this? I have an example below of what I am trying to do. https://code.sololearn.com/cTBMT9mYJmDl
7 Respuestas
+ 5
"strncpy" will be your go-to guy here, I think.
The question is always: Who owns the string? By your struct definition, you want this to be the struct (which makes sense). If you come from a pointer to char as function argument, you cannot be sure about the lifetime of your string. Having a char* in the struct may lead to a dangling pointer if the referent is being discarded, or changed from under the struct if for example the argument was a ref to a static buffer that is overwritten in the next input. Thus, while char* is a viable option, you might still want to duplicate your string to claim ownership.
+ 3
Ipang yes, that is absolutely correct 👍
+ 3
Ani Jona 🕊
Thanks so much 🙏
+ 3
You're welcome :)
+ 2
I'm not too sure about compiler compatibility, but use of char* as <name> member's type in SoloLearn's Code Playground seems to work.
Line 8:
char* name;
Let's hear what Community has to say : )
+ 2
Ani Jona 🕊
Can we safely conclude that struct member <name> initialization was only possible using C-String literal, but not C-String variable?
+ 2
Thank you @Ani_Jona for explaining it and @Ipang for summarising for simplicity!