2014-10-06 14 views
0

我有一些代碼提示用戶閱讀具有以下格式的文件:[name] [someInt],但並非所有行都具有[name]。因此,我將每行解析爲一個字符串數組,如果它的長度爲2,則它有一個名稱並執行一個strcmp來查找匹配,然後打印出相關的int。但是,我遇到了一些問題,在這裏我得到試圖設置和打印指針的值

error: invalid operands to binary * (have ‘char *’ and ‘char *’)

printf("%s\n" *ans);

char * ans = NULL; 

//open and read file line by line, below code is in line by line while loop 
      char ** res = NULL; 
      char * p = strtok (line, " "); 
      int n_spaces = 0, i; 
      while (p) { 
       res = realloc (res, sizeof (char*) * ++n_spaces); 

       if (res == NULL) { 
        exit (-1); /* memory allocation failed */ 
       } 

       res[n_spaces-1] = p; 
       p = strtok (NULL, " "); 
       printf("%d\n", n_spaces); 
       if(n_spaces == 2 && (strcmp(name,res[0]) == 0)) { 
        nameMatch = true; 
        printf("MATCH FOUND!\n"); 
        ans = res[1]; 
        printf("%s\n" *ans); 
        break; 
       } 
      } 

回答

1
printf("%s\n" *ans); 
      ^

你錯過了這些參數之間的逗號。編譯器將*解釋爲乘法,並不理解您希望它如何乘以兩個字符串。

即使有這種變化,你會(可能?)仍然會收到關於類型的警告。完全刪除*;我很確定你想傳遞字符串指針到printf,而不是字符串的第一個字符。

0

你是在告訴水庫爲NULL編譯時。那麼,在malloc之前,你正在使用realloc?你的錯誤可能是這個。

+0

'realloc(NULL,size)'完全沒問題。它被定義爲等同於'malloc(size)'。 – duskwuff 2014-10-06 22:39:09

-1

printf("%s\n", *ans);代替printf("%s\n" *ans);