开发者

C string problem

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 dat开发者_如何学运维a structure
    ...
  }
}

Clarification: the question is how can I assign the name to this new person inside p *addNewPerson(char *name)?


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.


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;
}


  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.


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.


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;
}


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.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜