tags:

views:

183

answers:

7

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)?

+1  A: 

Use strcpy to copy the string and store it in your struct:

strcpy(p->name, name);

Also remember to check the string length so that it fits in name without overflowing.

You
+3  A: 
p *newPerson = (p *)malloc(sizeof(person));
//here how can I assign the name to this new person?

You would do this:

strcpy(p->name,name);

You should also change your use of p to struct person since p is not a type, it is a global veriable of type struct person . Change the code to:

struct person *addNewPerson(char *name)
{
   struct person *newPerson = malloc(sizeof *newPerson);

//shoud I do something with this "input", like input[strlen(input)-1] =

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:

  int ret = scanf("%24s",buffer);  //read max 24 chars, to make space for a final '\0'
  if(ret == EOF) { //end of input reached.
     break; 
  if(ret != 1) {
    // for whatever reason, the conversion failed. exit, or alert the user, or whatever
  }

Similarly inside your addNewPerson at the strcpy(p->name,name); , strcpy might happily write past the buffer if the name is longer than what p->name can 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 buffer directly, when used as a value, the name of an array decays to a pointer to the first element of that array;

 struct person *newPerson = addNewPerson(input);

Since newPerson is dynamically allocated with malloc() , remember to free() it when you no longer need it. Otherwise you will leak memory.

nos
To add to this answer: scanf can cause some security issues with buffer overflows. Check http://www.cprogramming.com/tutorial/secure.html and try using fgets w/ stdin
SB
scanf parameters take a width type that will stop the input array being overwritten by two much input. "%24s"
Martin York
Unchecked calls to `strcpy()` can also cause buffer overflows.
Jonathan Leffler
+1  A: 
  1. You can assign the name member by sprintf(p->name, "%s", name);, but you should be wary of overflowing the 25 character buffer. For instance, you could do snprintf(p->name, 25, "%s", name);

  2. The most important thing you should learn in writing this program is that anything you malloc() needs to be free()'d. Otherwise, you will cause memory leaks. At the end of main(), make sure to free(newPerson);. If you change your structure member to be a pointer, you will need to malloc it, and then free it whenever appropriate.

Jonathan
Using `sprintf` here is overkill; we're dealing with a string copy, not a string formatting operation. Well done pointing out the `malloc`/`free` thing, though.
You
A: 

You can do it two ways.

First, as you suggest, you can change the member name of person from an array to a pointer. Then in addNewPerson, you would just do:

p *newPerson = (p *)malloc(sizeof(person));
p->name = name;

EDIT: As noted in the comments, this is inherently bad, and you should be copying the bytes. I've been working in reference counting land too long.

Otherwise, you'll need to copy the bytes from the passed in name into your struct array. I would use strlcpy as such:

strlcpy(p->name, name, sizeof(p->name));

if available, otherwise use:

strncpy(p->name, name, sizeof(p->name));

The only difference being that you would have to null-terminate p->name if name was too long to fit into p->name.

bobDevil
The first is fundamentally flawed: pointing to a buffer passed by function parameter, no no.
Codism
A: 

I rather call the method constructPerson. This is actually a constructor in OOP jargon

struct person
{
  char *name; //can hold string of different sizes
}p;

p *addNewPerson(char *name)
{
  p *newPerson = (p *)malloc(sizeof(person));
 p->name= (char *) malloc(sizeof(char)*(strlen(name)+1));//don't forget to claim space for the '/0' character at the end of the string
 strcpy(p->name,name);
  return newPerson;
}
Dani Cricco
Off-by-one buffer overflow: `strlen(name)+1` or `strdup(name)`.
Jonathan Leffler
right!, tks for pointing it out. I fixed the post
Dani Cricco
+2  A: 

There is a fundamental flaw in your code which nobody hasn't picked up on yet which is worth noting. p is not a type, it is a variable declaration of type struct person. Your addNewPerson() function just would not work at all. Either change the addNewPersion() function appropriately:

struct person *addNewPerson(char *name)
{
    ...
}

or define the type p:

typedef struct person { ... } p;

Then use strcpy() (rather, I'd suggest strncpy() instead) as the others have suggested.

struct person *addNewPerson(char *name)
{
    struct person *newPerson = (struct person *)malloc(sizeof(struct person));
    //strcpy(newPerson->name, name);
    strncpy(newPerson->name, name, sizeof(newPerson->name)); //more safe
    return newPerson;
}
Jeff M
A: 

You need no strcpy, you need no malloc, you need no sizeof etc. IF you use an char-array in your struct, eg:

typedef struct {
char name[25];
} Person;

main() {
  Person person;
  char name[25];
  if( 1==scanf("%24s",name) )
    person=*(Person*)name;
  return 0;
}

or if you need more persons:

main() {
  Person person[2]={{"firstperson"}};
  char name[25];

  if( 1==scanf("%24s",name) )
    person[1]=*(Person*)name;

  puts( person[0].name );
  puts( person[1].name );

return 0;
}
That's quite a bold statement to make. It's not safe to play with pointers that way.
Jeff M
It will ever works on all ANSI C environments; tell me one non working system/compiler please
Sorry, poor choice of words there since I last edited my comment. Yes it would work but I would consider this approach more of a hack than a proper way to deal with the question at hand. Of course if `Person` was more complex, it would require tweaks, but it is still a hack.
Jeff M
the question was: string-handling in structs; my solution is safer than strcpy/strncpy eg. for uninitialized contents in Person.name. For more complex structs its the same: typedef struct {char name[25];} Name25; typedef struct {Name25 a; int i; Name25 b;} ComplexPerson; and ... ComplexPerson p; p.a=*(Name25*)name;...p.b=*(Name25*)name; ... and it will ever work for any contents of name in contrast to your favorite strcpy-solution: they is undefined for undefined name-contents. implicit struct-content-copy is well known ANSI C not a hack/trick/tweak/...
The question being asked was essentially how to copy a string from one location to another. What you suggested didn't directly address this but instead, relied on another property of the language based on the example code to perform the action. Would you have suggested the same if the OP gave 2 buffers instead and asked the same question? This prompted my comment.
Jeff M