gpt4 book ai didi

c - 使用c中的指针初始化结构体的构造函数值

转载 作者:行者123 更新时间:2023-11-30 14:34:37 26 4
gpt4 key购买 nike

#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char name[50];
int year_of_birth;
char sex[7];
char father[50];
char mother[50];
char significant_other[50];
char children[50];
};

struct Person* person_constructor(char *name, int year_of_birth, char *sex);

int main(){

struct Person* p1 = person_constructor("Abbas", 1970, "male");

}

struct Person* person_constructor(char *name, int year_of_birth, char *sex) {
struct Person *p;
printf("%s",*name);
printf("%s",*sex);
printf("%d",&year_of_birth);
// how to initalise these here and return name, age and sex everytime , can you tell me in print function
}

我想做:Person* person_constructor(char *姓名, int 出生年份, char *性别);具有给定参数的人并返回它。还分配内存。

最佳答案

在下面的示例代码中,您可以找到问题的可能解决方案之一。在 C 语言中,不可能返回多个变量,但您可以返回指向构造结构对象的指针,并使用符号 Stuct_ptr->struct_member 访问结构成员。

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char name[50];
int year_of_birth;
char sex[7];
char father[50];
char mother[50];
char significant_other[50];
char children[50];
};

struct Person* person_constructor(char *name, int year_of_birth, char *sex);

int main(){

struct Person* p1 = person_constructor("Abbas", 1970, "male");

/* it is not possible to return more variables in C */
/* you can use pointer to access members from constructed structure: */

printf("print from main:\n %s %d %s \n", p1->name, p1->year_of_birth, p1->sex);

if( p1 != NULL) free(p1); /* do not forget do deallocate something taht is allocated */
return 0;
}

struct Person* person_constructor(char *name, int year_of_birth, char *sex) {

struct Person *p = calloc(1, sizeof(struct Person));

if( p == NULL ) return p; /* memory alocation failed! */

strcpy(p->name, name);
p->year_of_birth = year_of_birth;
strcpy(p->sex, sex);

printf("print from constructor:\n");
printf("%s ",p->name);
printf("%s ",p->sex);
printf("%d \n",p->year_of_birth);
return p;
}

关于c - 使用c中的指针初始化结构体的构造函数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58899781/

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