首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >malloc内存指向指向指针的指针

malloc内存指向指向指针的指针
EN

Stack Overflow用户
提问于 2012-04-18 21:38:04
回答 4查看 706关注 0票数 1

我在使用指向字符的指针时遇到了这个问题:

代码语言:javascript
复制
void setmemory(char** p, int num)
{
    *p=(char*)malloc(num);
}

    void test(void)
    {
        char* str=NULL;
        setmemory(&str,100);
        strcpy(str,"hello");
        printf(str);
    }

int main()
{
    test();
    return 0;
}

上面的代码是正确的,但是我不明白为什么在这里使用指针char** p?为什么只使用指向char的指针呢?所以我把这段代码改成了下面,发现它不能工作,有人能告诉我为什么吗?谢谢!

代码语言:javascript
复制
void setmemory(char* p, int num)
{
    p=(char*)malloc(num);
}

void test(void)
{
    char* str=NULL;
    setmemory(str,100);
    strcpy(str,"hello");
    printf(str);
}

int main()
{
    test();
    return 0;
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-04-18 21:43:41

这里要注意的一件事是-当我们说到pass by reference时,我们通常倾向于从pass by reference的角度来思考,但不一定。即使是指针也可以是 passed by value

char* str对于test是本地的,char* p对于setmemory是本地的。因此,如果您不发送指向指针的指针,则在setmemory中所做的更改将在test中不可见。

您可以使用单个指针使其工作,如下所示

代码语言:javascript
复制
 char * setmemory(char* p, int num) // p is a new pointer but points at the same
                                    // location as str
{
    p=(char*)malloc(num); // Now, 'p' starts pointing at a different location than 'str'
    strcpy(p ,"hello");  // Copy some data to the locn 'p' is pointing to
    return p; // Oops. The poor `str` is still pointing at NULL :( 
              // Send him the address of the newly allocated area
}

void test(void)
{
    char* str=NULL;
    str=setmemory(str,100); // We are passing a pointer which is pointing to NULL

    printf(str); //Now str points to the alloced memory and is happy :)
}

int main()
{
    test();
    return 0;
}

注意,在setmemory中,我们返回一个本地指针,但这不是问题(没有悬空指针问题),因为该指针指向堆上的位置,而不是堆栈上的位置

票数 3
EN

Stack Overflow用户

发布于 2012-04-18 21:43:33

你想改变指针,即函数需要一个引用,而不是一个值。在C中,这是通过给变量提供地址(指针)来完成的,也就是通过改变指针本身。因此,一个指针用于引用,另一个用于程序逻辑。

票数 0
EN

Stack Overflow用户

发布于 2012-04-18 21:48:53

您在这里只设置了局部变量*p。记住,你得到的是一个指向数据的指针,而不是指向数据的指针。

你可以这样想:

第一种情况:

代码语言:javascript
复制
int a;

foo(a); // Passes a
void foo(int b)
{
  b = 4;    // This only changes local variable, has no effect really
}

第二种情况:

代码语言:javascript
复制
int a;
foo(&a); // Passes *a

void foo(int *b)
{
  *b = 4; // This changes the contents of a. As you can see we have not changed the original pointer!
  b = 4; // This changes our local copy of the pointer, not the pointer itself, like in the first case!
}

第三种情况

代码语言:javascript
复制
int *ptr;
foo(&ptr); // Passes **ptr

void foo(int **b)
{
  **b = 4; // This changes the data of the passed pointer
  *b = 4; // This changes the passed pointer itself, i.e. it changes ptr. This is what test() is doing, the behavior you are looking for!
  b = 4; // This changes our local copy of a variable, just like the first case!
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10210587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档