从函数中返回一个数组(C编程)

3

我正在尝试制作一个向量的图像(学校练习),因此我正在使用标题。

有两个文件和一个函数。

首先,我创建了一个向量。

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)

我的数据丢失了,我不知道如何传回我一直在处理的向量(我需要返回这个向量以获取错误代码)。


正如你所说,它已经丢失了,因为你只覆盖了由main传递的变量的本地副本,现在这个变量是悬空的,因为你将它的值传递给了free - Weather Vane
1个回答

1
你需要做的是传递一个指向字符数组vectorPhotography的引用,这样在函数调用之后就可以访问更新后的值。这将涉及更改函数签名为int seeVector(Vector * vector, char ** vectorPhotography),更改函数调用为seeVector( &vector, &vectorPhotography ),然后更改函数内部对 vectorPhotography 的使用为 *vectorPhotography,以便更改由本地参数指向的值。

你是对的,谢谢。向量测试器 作者:Oz Pineapple 向量已初始化 向量:{ 大小:, 数组:[][][], } 有新问题,但我可以自己解决 UwU - OzPineapple

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接