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

标签 c

<分区>

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

最佳答案

您的 merge() 代码要求数组以零结尾。调用代码没有执行此操作,因此行为未指定(我在尝试您的代码时遇到了段错误)。

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

(*arr1)++;

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

关于c - 在函数中使用指针的指针的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10058287/

相关文章:

c - 线程产生相同的随机数?

c - 在 C 中,如何从另一个数组中删除一个数组中存在的所有字符?

c++ - 如何推送字符数组?

c - 同名输入/输出问题

c - #定义奇怪

c - 如何稳健地写入缓慢且不可靠的 NFS

c - 不带 "return"命令返回

c - 使用 SDL_strdup 和类似工具获取文件名时出现问题

c - 多线程应用程序在 printf 中挂起?

c++ - 如何从 mex 函数返回矩阵结构?