gpt4 book ai didi

c - 如何在 struct 中为 char* 字段分配内存

转载 作者:太空宇宙 更新时间:2023-11-04 06:55:39 25 4
gpt4 key购买 nike

如何为结构中的 char * 字段分配内存?

我的结构:

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

}

如何 malloc 到 char* namechar* surname
我必须有一个结构数组,格式为struct student st[]

我不知道,如何合理地做到这一点。

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

如何匹配这个?

最佳答案

例如

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

您可以编写单独的函数来设置数组元素的数据成员名称和姓氏。

例如

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

关于c - 如何在 struct 中为 char* 字段分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45237454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com