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

标签 c pointers structure

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

相关文章:

c - 如果出错我该如何返回 - C

带星号的 C 函数签名

c++ - 结构/对象内的存储顺序

python - 关于Python概念层次的问题

c - C 中不关闭冲水管

C fscanf 和指针

c++ - 将动态二维数组的返回指针传递给子函数并寻址该数组

c++ - .net c++/cli 获取指针的内容

c++ - 如何在 C++ 中动态声明一个指向整数的指针数组?

c - 使用 qsort() 对结构指针数组进行排序时程序崩溃