我们可以在函数中初始化一个指针,并且在C的main函数中仍然存储相同的地址吗? [英] Can we initialize a pointer in a function and still the same address is stored in the main function in C?

查看:29
本文介绍了我们可以在函数中初始化一个指针,并且在C的main函数中仍然存储相同的地址吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

main()
{
    struct MyList *list = NULL;

    int flag = MyListInit(list);
}

int MyListInit(MyList* list)
{
   list = malloc(sizeof(struct MyList));
   if (list != NULL) {
       return 1;
   }
   return 0;
}

在调用函数之后,我希望列表保存一个内存地址,该地址在调用malloc时分配.但是它的值为NULL,但是在运行Mylistinit函数的过程中,list的值不会为NULL,但是在返回后,它将被更改回NULL.

After the function is called I want the list to hold a memory address which is allocated when malloc is called. But its value is NULL, but during runtime in the Mylistinit function, the value of list wont be NULL, but after returning, it will be changed back to NULL.

我不想从函数返回地址,我必须返回一个整数(对此进行确认)

I do not want to return the address from function, I have to return an integer(firm on this)

推荐答案

由于所有变量均通过值甚至指针传递,因此您必须使用像这样的双指针,并且应该强制转换为(MyList *)类型.

Since all variables are passed by value even pointers you must used a double pointer like this and You should cast to type (MyList*).

int MyListInit(MyList**); // function declaration
int main(){

   struct MyList *list = NULL;

   int flag = MyListInit(&list);
   return 0;
}

int MyListInit(MyList** list)
{
     *list = (MyList*)malloc(sizeof(struct MyList));
     if (list != NULL) return 1;
     return 0;
{

这篇关于我们可以在函数中初始化一个指针,并且在C的main函数中仍然存储相同的地址吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆