c - 将指针分配给函数或将其地址作为函数参数传递之间有什么区别吗?

标签 c pointers malloc

我真的不知道怎么问更合适,但我会尽力解释我的问题。

假设我们有以下内容:

int *ptr = foo(&ptr);

这对我来说,我相信这意味着,有一个声明初始化到函数foo,它自己用作指针函数参数。

现在是:

int *ptr = foo();

我认为是相同的,但没有任何函数参数,这意味着函数 foo 不接受任何参数。

现在让我们看一下以下两个程序:

程序 1:

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

#define SIZE 3

int *foo(int **ptr);

int main(void){
    int *ptr = foo(&ptr);

    for (int i=0 ; i<SIZE ; i++){
        *(ptr + i) = i + 1;
    }

    for (int j=0 ; j<SIZE ; j++){
        printf("%d\n",*(ptr + j));
    }

    free(ptr);
}

int *foo(int **ptr){
    *ptr = malloc(SIZE * sizeof(*ptr));
    if(*ptr == NULL){
        printf("Error, malloc\n");
        exit(1);
    }
    return *ptr;
}

程序 2:

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

#define SIZE 3

int *foo(void);

int main(void){
    int *ptr = foo();

    for (int i=0 ; i<SIZE ; i++){
        *(ptr + i) = i + 1;
    }

    for (int j=0 ; j<SIZE ; j++){
        printf("%d\n",*(ptr + j));
    }

    free(ptr);
}

int *foo(void){
    int *ptr = malloc(SIZE * sizeof(*ptr));

    if(ptr == NULL){
        printf("Error, malloc\ņ");
        exit(1);
    }
    return ptr;
}

程序 1程序 2 的区别/优势是什么。

第一个或第二个程序中的指针是否受到某种不同的影响?或者是否有使用 program 1program 2 的任何原因?

我在问,因为如何编程的方式看起来 program 1program 2 是一样的。

编辑: 我知道第一个程序的指针 ptrfoo 函数修改,在第二个程序中我在函数 foo 中声明它,但是这不是我的问题。

最佳答案

这两个程序之间唯一实际的区别是第一个可以分配比第二个多一倍的内存。

在第一个程序中,您使用 *ptr 来获取大小,但是 *ptrint * 类型,在 64-位系统通常是64位。在第二个程序中,*ptr 是一个 intint 的大小在 32 位和 64 位系统上通常都是 32 位。

由于第一个程序模拟通过引用传递,您可以在不使用返回指针的情况下使用它,事实上它根本不需要返回值并且可以声明为返回 无效。首选哪个是个人选择,我个人更喜欢第二种选择,但这也取决于用例。

关于c - 将指针分配给函数或将其地址作为函数参数传递之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36157486/

相关文章:

C编程: padding in structure

c - _CrtIsValidHeapPointer(pUserData) 错误 : Realloc() pointer

c - libmodbus : modbus_mapping_new() not working correctly?

objective-c - 在预处理器宏中包装内联 C 函数

c - 如何在函数调用时正确迭代链表

C链表指针问题

c - 在 C 中使用指针将数组传递给函数?

c - malloc 之后的 while 循环后出现段错误

将结构复制到动态分配的结构数组中

c - 双重免费或腐败崩溃