How to pass strings into structs (C) (SOLVED) | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 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

10th May 2022, 4:47 AM
Cam UOR
Cam UOR - avatar
7 Antworten
+ 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.
10th May 2022, 5:22 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 3
Ipang yes, that is absolutely correct 👍
10th May 2022, 7:17 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 3
Ani Jona 🕊 Thanks so much 🙏
10th May 2022, 7:19 AM
Ipang
+ 3
You're welcome :)
10th May 2022, 7:27 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 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 : )
10th May 2022, 5:10 AM
Ipang
+ 2
Ani Jona 🕊 Can we safely conclude that struct member <name> initialization was only possible using C-String literal, but not C-String variable?
10th May 2022, 5:46 AM
Ipang
+ 2
Thank you @Ani_Jona for explaining it and @Ipang for summarising for simplicity!
11th May 2022, 6:55 AM
Cam UOR
Cam UOR - avatar