2013-04-06 93 views
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编码本文档是有用的,这是一个好的做法呢?

+0

请查看关于[引用调用]的解释(http://en.wikipedia.org/wiki/Call-by-reference#Call_by_reference) – Bechir 2013-04-06 13:11:58

回答

0

你传入两个int和一个指针(第三个参数)的地址,你应该接受前两个参数中的指针(一个*)为int和第三个参数的指针为int的指针(二**):

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

在负载功能,您可以将值分配给*n*x,因为这两个指向有效的内存地址,但你不能做**arr = 10只是因为arr不指向任何内存(指向NULL),所以第一你有t o首先为*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 
} 

参考:for document practice

编辑如你评论,不喜欢以下我正在写,它不会给出任何错误/因为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:

“从无效皈依无效*为int *” 时我更改为ARR = malloc的( sizeof(int)(* n));

syntax of malloc():

​​

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

但我避免铸造时的malloc(),因为:Do I cast the result of malloc?阅读Unwind的回答

+0

为什么* arr = malloc(sizeof(int)* n)doesn'工作? (类型的操作数无效) – user2251921 2013-04-06 12:53:11

+0

@ user2251921你声明像'int ** arr'吗?以前我犯了错误。 – 2013-04-06 12:55:54

+0

是的,它说:“无效的从void *到int *的转换”当我将其更改为* arr = malloc(sizeof(int)*(* n))时; – user2251921 2013-04-06 13:00:08