在函数中使用指针指针的正确方法是什么?

时间:2012-04-07 20:52:39

标签: c

我使用的函数显示指针指向的内存块内容。 但没有得到所需的输出,我是新来的,请纠正我,如果我错了。 当我输入size = 3,element = 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++;
    }
}

1 个答案:

答案 0 :(得分:3)

您的merge()代码需要将数组终止为零。调用代码没有这样做,因此行为未指定(我在尝试代码时遇到了段错误。)

另一个问题是你应该在*arr1附近加上括号:

(*arr1)++;

当我使用此修改运行代码并为最后一个元素输入零时,您的代码运行正常。

相关问题