Tuesday, July 14, 2009

How do I set their name (C programming):?

typedef struct Man {


char Name[31];


...


}Character;





Character Person;

How do I set their name (C programming):?
The other two are incorrect. These are character arrays not C++ strings. You must use strcpy.


strcpy(Person.Name, "someone");


or perhaps better


strncpy(Person.Name, "someone", 31);
Reply:Person.Name='NAME';
Reply:Person.Name='John';
Reply:You'll need to use a function like strcpy() to copy the string into the array inside the struct, for instance:





char myName[] = "HandsOnDataStructures";





strcpy( Person.Name, myName);
Reply:Person.Name = "blah";
Reply:To initialize the variable at the time you declare it:





Character Person = {"John Smith"};





The above code only works when you're declaring and initializing at the same time. To assign a name after it's been declared, without risking overwriting memory that doesn't belong to the struct:





strncpy(Person.Name, "John Smith", sizeof Person.Name);





The problem with the above is that if "John Smith" is too big to fit in the array Person.Name, it will be truncated. This is probably not what the programmer really wants. To do it properly and safely, assuming the name is pointed to by inputName:





if (strlen(inputName) + 1 %26lt;= sizeof Person.Name)


strcpy(Person.Name, inputName);


else


/* print an error message and attempt to get a shorter name */

snow of june

No comments:

Post a Comment