【问题标题】:Pointer of a pointer as function argument指针的指针作为函数参数
【发布时间】:2018-01-07 05:43:16
【问题描述】:
   typedef struct rilevamenti {
   char     idStazione[4];
   ...
   struct   rilevamenti* next;
} rilevamenti_t;

void push (rilevamenti_t ** head, char id[], char nome[], char codice[], float quant, char data[]);


int main(int argc, char **argv)
{

    FILE *fp;
    char    tmpIdStazione[4];
    char    tmpNomeParametro[200];
    char    tmpCodiceParametro[6];
    float   tmpQuantita;
    char    tmpData[8];


    fp = fopen("file1.txt", "r");
    if(fp == NULL) 
    {
    perror("Error in opening file1.txt");
    return(-1);
    }

    rilevamenti_t * lista1 = NULL;


   while(1){

           fscanf(fp, "%s", tmpIdStazione);
           printf("Stazione: %s\n", tmpIdStazione );
           ...

           push (lista1, tmpIdStazione, ...);

        if( feof(fp) ) { 
         break ;
      }
   }
    fclose(fp); 

    return 0;
}


void push(rilevamenti_t ** head, char id[], char nome[], char codice[], float quant, char data[]) 
{
    rilevamenti_t * new_rilevamento;
    new_rilevamento = (rilevamenti_t *)malloc(sizeof(rilevamenti_t));

    strncpy(new_rilevamento->idStazione, id, 4);
    ...
    *head = new_rilevamento;
}

我认为我在调用推送功能时遗漏了一些东西, 我的想法是将列表的头指针作为指针传递, 所以我可以从列表的头部一个一个地添加所有的列表结构,只需要改变第一个指针。

但我很震惊,老实说,在使用了大量 java 和 C# 之后,我对 C 有点生疏了:/

我设置“...”只是为了让代码更短,我在这里列出所有结构的成员并一一填写。

【问题讨论】:

    标签: c function pointers arguments


    【解决方案1】:

    在这种情况下传递rilevamenti_t* 的地址&lista1。会是

    push (&lista1, tmpIdStazione, ...);
    

    在您遇到类型不匹配之前。而且您正在传递一个单指针(rilevamenti_t *),其中需要双指针(rilevamenti_t**)。这导致了未定义的行为。(您正在取消引用 NULL)。

    不要强制转换malloc 的返回值并检查malloc 的返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 2011-02-04
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多