开发者

c Pointer to pointer, or passing list to functions

开发者 https://www.devze.com 2023-01-02 14:26 出处:网络
I am new to c programming. Could anyone please tell me what\'s wrong with the following program? typedef struct Person_s

I am new to c programming. Could anyone please tell me what's wrong with the following program?


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


int process_li开发者_开发知识库st(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;
}


Your problem is that you're setting the pointers to point to NULL (0), then dereferencing them. You are not allowed to dereference NULL. Want you want is more like this:

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...

The & is the "address-of" operator, which returns a pointer to the variable's address. So this passes a pointer to count and p_list, which your function then uses to set those variables, which appears to be what you want to do.


You should have in main:

Person_t *p_list=0;
...
process_list(count, &p_list);

The code as written passes in 0 to process_list, and then you have:

*0 = (Person_t *)malloc(...);

This causes 0 to be dereferenced, and your code will crash.


The value of p_list as you enter the function is 0. If you dereference 0 you get a Bus Error.

if(!((*p_list) = (Person_t *) malloc(sizeof(Person_t))))

(90% of C problems are caused by dereferencing a null pointer, just like 90% of Java problems are caused by a misconfigured classpath. :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号