My problem is very simple, but I really don’t know how to manipulate strings in C
The problem is:
I have a struct called person
struct person
{
char name[25] // use char *name better?
}p;
I also have a function called p *addNewPerson(char *name)
p *addNewPerson(char *name)
{
p *newPerson = (p *)malloc(sizeof(person));
//here how can I assign the name to this new person?
...
return newPerson;
}
So, in the main function
void main()
{
for(; ;)
{
char input[25];
scanf("%s", input); // is this way possible?
//shoud I do something with this "input", like input[strlen(input)-1] = '\0'
//call addNewPerson()
p *newPerson = addNewPerson(&input);
//store this newPerson in some data structure
...
}
}
Clarification: the question is how can I assign the name to this new person inside p *addNewPerson(char *name)?
You would do this:
You should also change your use of
ptostruct personsincepis not a type, it is a global veriable of typestruct person. Change the code to:No, scanf will nul terminate the string for you.
Be aware though, string handling in C needs to be done very, very carefully.
e.g. when you do
scanf("%s", input);, what happens if you enter a name longer than 24 characters ?Anything might happen. scanf might overflow your buffer, and you get undefined behavior. You should do atleast this:
Similarly inside your
addNewPersonat thestrcpy(p->name,name);, strcpy might happily write pastthe buffer if the
nameis longer than whatp->namecan hold. In this particular case, with the above modification to scanf, the length will always be 24 or less so it’s safe. But be very aware of this in general .The call to addNewPerson should just pass the name of
bufferdirectly, when used as a value, the name of an array decays to a pointer to the first element of that array;Since
newPersonis dynamically allocated with malloc() , remember to free() it when you no longer need it. Otherwise you will leak memory.