c - 从函数传回数组(C 编程)

标签 c function pointers reference header

我正在尝试制作 vector 图像(学校练习),所以我使用了标题。 有两个文件和一个函数。

首先我做了一个 vector

Vector vector;
GLOBAL_ERROR_CODE = initVector(&vector,3);
if(GLOBAL_ERROR_CODE>0) return printGlobalError();                                          
printf("Vector inited\n"); 

稍后尝试打印它

char * vectorPhotography;
GLOBAL_ERROR_CODE = seeVector( &vector, vectorPhotography );
if(GLOBAL_ERROR_CODE>0) return printGlobalError();                                           

所以 seeVector 函数就是这个

int seeVector(Vector * vector, char * vectorPhotography){
     char * vectorStrSize = (char *) malloc(sizeof(char));
     int ErrorCode = integerToString(vector->size, vectorStrSize);
     if(ErrorCode>0) return ErrorCode;
     char * arrayPhotography = (char *) malloc(sizeof(char));
     if(ErrorCode>0) return ErrorCode;
     ErrorCode = seeArray(vector->array, arrayPhotography, vector->size);
     if(ErrorCode>0) return ErrorCode;
     if(vectorPhotography) free(vectorPhotography);
     vectorPhotography = (char *) malloc(sizeof("{\nSize:,\nArray:,\n}") + sizeof(arrayPhotography) + sizeof(vectorStrSize));
     if(vectorArray == NULL) return RESERVE_MEMORY_FAIL;
     strcat(vectorPhotography, "{\nSize:");
     strcat(vectorPhotography, vectorStrSize);
     strcat(vectorPhotography, ",\nArray:");
     strcat(vectorPhotography, arrayPhotography);
     strcat(vectorPhotography, ",\n}");
     return 0; 
}

事情是这样的,在算法之后的 seeVector 函数中,vectorPhotography 的值是这样的

(gdb) print vectorPhotography 
$3 = 0x5555557576f0 "{\nSize:\003,\nArray:[][][],\n}"

但是当我返回主函数时,值是 NULL

(gdb) print vectorPhotography
$4 = 0x0

在运行时我明白了

Vector inited
Vector:(null)

所以我的数据丢失了,我不知道如何传回我一直在处理的 vector ,(我需要返回错误代码)

最佳答案

您应该做的是传递对 char 数组 vectorPhotography 的引用,以便您可以在函数调用后访问更新后的值。这将涉及将您的函数签名更改为 int seeVector(Vector * vector, char ** vectorPhotography),将您的函数调用更改为 seeVector( &vector, &vectorPhotography ),然后更改您的vectorPhotography 在函数内部的用法为 *vectorPhotography 因此您可以更改局部参数指向的值

关于c - 从函数传回数组(C 编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61083191/

相关文章:

c - 是否可以在 Windows 中打开匿名文件?

c++ - Unix 数据报套接字仅适用于第一帧

c - C 中的列表按字母顺序排列,额外输入

Javascript - 数组上的函数混淆

java - 游戏的平均得分。要么除以零,要么计算太多

c - 不输入我的人名功能。我放置函数和所有内容的方式是否符合逻辑?

android - 在android中用指针绘制图表

c - 指向接收不需要的垃圾值的单独函数中的数组的指针

c - 在 C 中有效地编辑文件中的单个值

algorithm - 当 f(n) = O(n!) 且 k=n*(n-1) 时 f(k) 的复杂度