|
-
May 16th, 2005, 07:41 AM
#1
Thread Starter
Frenzied Member
struct problems
Hi
I have the following struct:
Code:
struct player{
char *name; // Name
int score; // Current score
int bonus; // Number of bonuses(ekstratur)
};
Then I fill it:
Code:
int i = 1; // Loop counter var
char *name = NULL;
int main(void)
{
printf("Indtast antallet af spillere: ");
scanf("%d",&players);
typedef struct player player;
player play[players];
for(i = 1; i<=players; i++){
printf("Indtast spiller %d's navn: ",i); // Prompt for name
scanf("%s",&name); // Write name
play[i].name = name; // Store name in player
play[i].score = 0; // Write score (reset)
play[i].bonus = 0; // Write bonus (reset)
} // End for
Now I try to get the name of one of the players:
Code:
printf("%s",play[0].name);
The printed string is blank.....can someone see the error?
-
May 16th, 2005, 08:45 AM
#2
Re: struct problems
When you do:
play[i].name = name;
Only the pointer to the buffer is changed, the char* should first point to a valid char[]. Here are some solutions:
1. Switch to C++ and preserver your sanity. Your code is not valid C98 anyway (// comments and intialization not at the top of a function), you might as well use full C++.
2. Allocate a buffer for each player's name using malloc, don't forget to free it when you are done.
3. Declare a static buffer inside the struct:
Code:
struct Player {
char name[500];
};
if you do this, you MUST check that the name is actually shorter then 500 characters, this can be done by specifying "%499s" as the format for scanf.
-
May 16th, 2005, 12:17 PM
#3
Thread Starter
Frenzied Member
Re: struct problems
Thanks, I'll try that 
PS: Have to use C, since íts a C course
-
May 16th, 2005, 12:37 PM
#4
Thread Starter
Frenzied Member
Re: struct problems
could u give an example...i have tried the following, but get conflicting types error:
Code:
char* str_name;
char name[100];
str_name = &name; // Have the pointer point to a char
-
May 16th, 2005, 12:57 PM
#5
Frenzied Member
Re: struct problems
char* str_name;
char name[100];
str_name = name;
Name is a pointer, thats why it didn't compile.
-
May 16th, 2005, 01:44 PM
#6
Thread Starter
Frenzied Member
Re: struct problems
i have also tried that, but don't work either...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|