c 指向指针的指针,或将列表传递给函数

标签 c pointers

我是 C 语言编程的新手。谁能告诉我有什么问题 以下程序?


typedef struct Person_s
{
  int age;
  char name[40];
} Person_t;


int process_list(int *countReturned, Person_t **p_list)
{

  Person_t *rowPtr=0;
  //the actual program will fethc data from DB

  int count =1;

 if(!((*p_list) = (Person_t *) malloc(sizeof(Person_t))))
 {
    return -1;
 }

 rowPtr = *p_list;

 rowPtr[count-1].age =19;
 strcpy(rowPtr[count-1].name,"Prince Dastan");
 *countReturned = count;

  return 0;
}


int main(int argc, char *argv[])
{
        Person_t *tmpPerson=0;
        Person_t **p_list=0;
        int *count=0;
        int i;

        process_list(count,p_list);

        tmpPerson = *p_list;

        for(i=0; i< *count; i++)
        {
           printf("Name: %s , age: %d\n",tmpPerson->name,tmpPerson->age);
           tmpPerson++;
        }

        //free(tmpPerson);

  return 0;
}

最佳答案

您的问题是您将指针设置为指向 NULL (0),然后取消对它们的引用。不允许取消引用 NULL。你想要的更像这样:

int main(int argc, char *argv[])
{
        Person_t tmpPerson;
        Person_t *p_list=0;
        int count;
        int i;

        process_list(&count, &p_list);

        tmpPerson = *p_list;
        // and so on...

& 是“寻址”运算符,它返回指向变量地址的指针。因此,这会传递一个指向 countp_list 的指针,然后您的函数会使用它们来设置这些变量,这似乎是您想要执行的操作。

关于c 指向指针的指针,或将列表传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3001259/

相关文章:

c - 将项目推送并附加到 C 中的链接列表中

c - 将 const 指针传递给结构 vs 按值传递

objective-c - 将字符串转换为 float ,而不使用 c 中的内置函数

c - 如何编写宏以返回逗号和整数或什么都不返回

c - epoll 是线程安全的吗?

c++ - 为什么函数调用后指针不为空?

c - 返回一个偶数递归

将 OpenOffice/Libreoffice 与代码文档的 Doxygen 结果结合起来?

c - 指针分配与元素或结构分配有什么区别?

c - 测试迭代指针之间的关系是否安全?