【问题标题】:Function that generates new structure data type and returns pointer生成新结构数据类型并返回指针的函数
【发布时间】:2017-08-19 05:31:07
【问题描述】:

我正在尝试制作一个程序,它创建一个结构的新数据类型 data_t。然后一个函数为堆上的新数据类型分配内存。然后我想改变 number 和 name 的值,我该怎么做呢?我试过的方法,好像不行:

  #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>

    typedef struct{
      char name[32];
      int number;
      char checksum;
    }data_t;


    data_t *new_data(char *name, int number){

      data_t *ptr=malloc(sizeof(data_t));
      strcpy(ptr->name ,name)
      (ptr->number)=number;



      return ptr; 

    }

【问题讨论】:

  • 我想这是因为data_t 只定义在new_data 的范围内,所以从函数外部的角度来看,返回类型没有意义。将结构定义移到外面。

标签: pointers struct malloc typedef


【解决方案1】:

您已经在函数内部定义了 struct。它不存在于函数之外。因此编译器显示未知数据类型错误。 将typedef 放在函数外。

【讨论】:

    猜你喜欢
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 2016-04-21
    相关资源
    最近更新 更多