2

main()函数中,我初始化了几个变量(intint*数组)。然后我打印出一些东西并从控制台读取它们scanf

我想将此功能放入一些外部函数中,以便主函数如下所示:

int main()
{
    int n = 0, x = 0;
    int *arr = NULL;    
    load(&n, &x, &arr);
}

load()函数调用之后,我希望变量与在函数内部设置的完全一样load()。我怎样才能做到这一点?

第二个问题,只是出于好奇:

/**
 * Description of the function
 *
 * @param int n Foo
 * @param int x Bar
 * @param int *arr Does something
 */
void load(int n, int x, int *arr)
{
    // something
}

该文档在 C 编码中有用吗?这是一个好习惯吗?

4

1 回答 1

0

您正在传递两个 int 和一个指针(第三个参数)的地址,您应该在指向 int 的指针(一个*)中接收前两个参数,并在指向 int 的指针(两个**)的指针中接收第三个参数:

void load(int* n, int* x, int **arr){
//           ^       ^ one*     ^ two **
    *n = 10;
    *x = 9;
}

在 load 函数中,您可以将值分配给*nand*x因为两者都指向有效的内存地址,但您不能**arr = 10仅仅因为arr不指向任何内存(指向 NULL)所以首先您必须首先为 分配内存*arr,喜欢:

void load(int* n, int* x, int **arr){
    *n = 10;
    *x = 9;
    *arr = malloc(sizeof(int));
    **arr = 10;
}

该文档在 C 编码中有用吗?这是一个好习惯吗?

是的

但有时我会通过以下方式记录我的函数参数:

void load(int n,     // is  a Foo
         int x,      // is a  Bar
         int **arr){ // do some thing 
    // something
}

参考资料:供文档练习

编辑正如您评论的那样,请像下面我写的那样,它不会给出任何错误/因为malloc().

#include<stdio.h>
#include<stdlib.h>
void load(int* n, int* x, int **arr){
    *n = 10;
    *x = 9;
    *arr = malloc(sizeof(int));
    **arr = 10;
    printf("\n Enter Three numbers: ");
    scanf("%d%d%d",n,x,*arr);
}
int main(){
    int n = 0, x = 0;
    int *arr = NULL;    
    load(&n, &x, &arr);
    printf("%d %d %d\n", n, x, *arr);
    free(arr);
    return EXIT_SUCCESS;
}

编译并运行如下:

~$ gcc ss.c -Wall
:~$ ./a.out 

 Enter Three numbers: 12 13 -3
12 13 -3

正如 OP 评论的那样:

“从 void* 到 int* 的无效转换”当我将其更改为arr = malloc(sizeof(int) (*n));

malloc() 的语法:

void *malloc(size_t size);  

malloc() 返回void**arr类型是int*编译器消息的原因,因为类型不同:"Invalid convertion from void* to int*"

但是我避免在 malloc() 时进行强制转换,因为:我会强制转换 malloc 的结果吗?阅读 Unwind 的回答

于 2013-04-06T12:48:16.063 回答