在我的main函数中有两个函数。
我试着用指针来解决这个问题,但是作为一个初学者,使用它是非常复杂的。
int main(){
int *p;
p = function_A();
function_B(p);
return 0;
}
int function_A(){
static int myArray[3];
myArray[0] = 11;
myArray[1] = 22;
myArray[2] = 33;
return myArray;
}
int function_B(int *myPointer){
// Here I just want to print my array I've got from function_A() to the
// console
printf("%d", *myPointer)
return 0;
}
function_A应该返回一个数组,而function_B应该接受这个数组。
谢谢!
发布于 2019-01-04 04:46:11
有些问题你的编译器已经告诉你了。首先,您应该在调用函数之前定义它们,或者至少向前声明它们。
其次,要返回数组,需要返回指向该数组第一个元素的指针,即返回类型是int *
而不是int
。
第三,正如FredK所指出的,当您只接收一个指针时,您没有机会确定它所指向的数组中有多少个元素。你可以用一个特定值结束数组,比如0
,或者你也需要返回数组的大小。
请参阅对您的程序所做的以下调整:
int* function_A(int *size){
static int myArray[3];
myArray[0] = 11;
myArray[1] = 22;
myArray[2] = 33;
if (size) {
*size = 3;
}
return myArray;
}
void function_B(int *myPointer, int size){
for (int i=0; i<size; i++) {
printf("%d\n", myPointer[i]);
}
}
int main(){
int *p;
int size=0;
p = function_A(&size);
function_B(p,size);
return 0;
}
发布于 2019-01-04 20:40:36
如果数组的大小确实是3(或其他较小的固定值),那么您可以简单地使用structs作为值,如下所示:
struct ints3 {
int values[3];
// if needed, can add other fields
}
int main(){
struct ints3 ints;
ints = function_A();
function_B(&ints);
return 0;
}
// note about function_A signature: void is important,
// because in C empty () means function can take any arguments...
struct ints3 function_A(void) {
// use C designated initialiser syntax to create struct value,
// and return it directly
return (struct ints3){ .values = { 11, 22, 33 } };
}
int function_B(const struct ints3 *ints) {
// pass struct as const pointer to avoid copy,
// though difference to just passing a value in this case is insignificant
// could use for loop, see other answers, but it's just 3 values, so:
printf("%d %d %d\n", ints->values[0], ints->values[1], ints->values[2]);
return 0; // does this function really need return value?
}
https://stackoverflow.com/questions/54029347
复制相似问题