C 将数据/结构传递给另一个函数并返回结构的引用

标签 c

  1. 如何在函数中返回 TITLE* 和 LEN* 类型的引用
  2. 如何将填充结构从一个函数传递到另一个函数(通过 main)

程序示例(仅示例未按我的预期工作):

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
TITLE *part_struct(char *line);
LEN *lenght(TITLE *title);

int main(){
      char line[]="Thomas,Bukurest";
      part_struct(line);      //this function must return reference on type TITLE*
      //when is structure filled with data I need to pass them to another function
      lenght(title);     //this does not compile and should return reference on type LEN*
      return 0;
}

typedef struct title {
      char* city;
      char* name;
}TITLE;

typedef struct len {
      int x;
      int y;
}LEN;      



TITLE *part_struct(char *line){           //this line must stay as it is
      TITLE *title = (TITLE*)malloc(sizeof(TITLE));
      char* buffer;
      char copy[20];
      strcpy(copy,line);
      buffer = strtok (copy,",");
      title->name=(char*) malloc(sizeof (char)*(strlen(buffer)));
      title->name=buffer;
      buffer = strtok (NULL, ",");
      title->city=(char*) malloc(sizeof (char)*(strlen(buffer)));
      title->city=buffer;
      return level;  //I am not sure if I am returning it as reference on type TITLE*
}



LEN *lenght(TITLE *title){     //this line must stay as it is
      LEN *len = (LEN*)malloc(sizeof(LEN));
      len->x=strlen(level->name);
      len->y=strlen(level->city);
      return len;
}

最佳答案

如何在函数中返回 TITLE* 和 LEN* 类型的引用。

TITLE *part_struct(char *line) {           //this line must stay as it is
   TITLE *title = (TITLE*)malloc(sizeof(TITLE));
   ...

   return(title);
   }

LEN *lenght(TITLE *title){     //this line must stay as it is
   LEN *len = (LEN*)malloc(sizeof(LEN));
   ...

   return(len);
   }

如何将填充结构从一个函数传递到另一个函数(通过 main)

int main(){
   char line[]="Thomas,Bukurest";
   TITLE *title = NULL;
   LEN   *len = NULL;

   title=part_struct(line);      //this function must return reference on type TITLE*
   //when is structure filled with data I need to pass them to another function
   len = lenght(title); //does not compile and should return reference on type LEN*
   return 0;   
}

关于C 将数据/结构传递给另一个函数并返回结构的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23187276/

相关文章:

c++ - 将c代码链接到c++代码时的g++链接顺序依赖性

C - 另一个 strtok() 和 free() 问题

c - 如何替换 time() 函数来测试生产库?

c - read() 函数中的随机空字符

arrays - 无法将char数组初始化为c中的变量

c - 使用socket进行文件传输和修改

c - 这个c代码行是做什么的? (const VAR = "string";)

python - 将数据数量/容量格式化为字符串

c - C语言结构体的动态内存分配

c - C中的整数到字符数组的转换