2012-04-07 80 views
1

我使用一个函数来显示指针指向的内存内容块。 但没有得到所需的输出,我是新来的,请纠正我,如果我错了。 当我输入大小= 3,元素= 1,2,3,我得到输出= 1只。在函数中使用指针指针的正确方法是什么?

下面的代码:

#include <stdio.h> 
#include <stdlib.h> 

void merge(int **arr1); 

int main(void) { 
    int size1; 
    printf("Give me the size of first array\n"); 
    scanf("%d", &size1); 

    int *arr1 = malloc(size1*sizeof(int)); 
    int *p1=arr1; 
    printf("Give me the elements of first array\n"); 
    int index1; 
    for(index1 = 0 ; index1<size1; index1++) 
    scanf("%d", p1++); 

    merge(&arr1); 
    return; 
} 

void merge(int **arr1) { 
    while(**arr1) //**arr1 is the content of the passed array, if there 
        // is an int in it, print that out and increment to next one 
    { 
     printf("%d", **arr1); // ** is the content and * is the address i think, right? 
     *arr1++; 
    } 
} 
+4

你得到了什么输出?你期望什么?你到目前为止做了哪些调试? – 2012-04-07 20:54:16

+2

请格式化您的代码。 – 2012-04-07 20:54:58

+0

对不起,我编辑它 – 2012-04-07 20:57:24

回答

3

merge()代码期望数组零终止。调用代码没有这样做,所以行为没有指定(当我尝试你的代码时,我得到了段错误)。

的另一个问题是,你应该把周围*arr1括号:

(*arr1)++; 

当我用这个修改就可以运行你的代码,并在最后一个元素输入零,你的代码运行正常。

+0

对,所以我想检查是否有任何有效的指针值,应该填写while语句? – 2012-04-07 21:05:26

+0

@qwrqwr一种方法是在'malloc'中分配一个额外的元素,并在循环后面放入零。当然,这可以防止用户输入零。如果这是一个问题,可以使用另一个数字作为“警卫”,或者将size1作为第二个参数传递给merge。 – dasblinkenlight 2012-04-07 21:07:37

+0

所以你说没有办法检查该元素是否有效,而不使用额外的大小参数? – 2012-04-07 21:11:24

相关问题