Reputation: 47
How to allocate memory for my char *
fields in struct ?
My struct:
struct student{
int score;
char* name;
char* surname;
};
int main(){
struct student st[];
int i;
int n = 5;
for(i = 0; i < n; i++){
printf("Score: \n");
scanf("%d", &st[i].score);
printf("Name \n");
scanf("%s", &st[i].name);
printf("Surname \n");
scanf("%s",&st[i].surname)
}
}
How to malloc to char* name
and char* surname
?
I must have an array of struct in form struct student st[]
.
I don't know, how do this rationally.
void initialise_student( struct student *st, char* name, char* surname)
{
st->name = ( strlen( name ) + 1);
st->surname = (strlen( surname ) +1 );
}
int main(){
int i;
int n = 5;
struct student *st[n] = initialise_student();
for(i = 0; i < n; i++){
printf("Score: \n");
scanf("%d", &st[i].score);
printf("Name \n");
scanf("%s", &st[i].name);
printf("Surname \n");
scanf("%s",&st[i].surname);
}
How to match this ?
Upvotes: 0
Views: 704
Reputation: 33704
If you are already using scanf
, you can tell the function to allocate the sting for you by using %ms
instead of %s
, like this:
char *name;
if (scanf("%ms", &name) != 1) {
fprintf(stderr, "error: could not read name\n");
exit(1);
}
EDIT This may not be a valid solution—I forgot that %ms
is in POSIX only, not in ISO C.
Upvotes: 0
Reputation: 310940
For example
#include <stdlib.h>
#include <string.h>
//...
struct student st[1];
char *name = "Marek";
char *surname = "Piszczaniuk";
st[0].name = malloc( strlen( name ) + 1 );
strcpy( st[0].name, name );
st[0].surname = malloc( strlen( surname ) + 1 );
strcpy( st[0].surname, surname );
st[0].score = 100;
You can write separate functions to set the data members name and surname for an element of the array.
For example
_Bool set_name( struct student *st, const char *name )
{
st->name = malloc( strlen( name ) + 1 );
_Bool success = st->name != NULL;
if ( success )
{
strcpy( st->name, name );
}
return success;
}
Upvotes: 3
Reputation: 234665
You need to write an initialise_student(struct student* s)
function which calls malloc
on the char*
members. Perhaps this function also takes the name
and surname
char* pointers
of which you take deep copies?
You then call this function with every member of the st
array.
Don't forget to build a corresponding free_student(struct student* s)
function.
Upvotes: 0