我正在尝试制作 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/