2012-07-12 40 views
1

我正在C中嘗試標記數組,然後將標記存儲到全局數組字符串。問題是,我正在嘗試使用指針來做到這一點,所以我不必查看字符串數組的索引。我知道陣列應該有多大,這就是爲什麼用索引很容易做到這一點,但是,我正在努力用指針來做到這一點。我不知道這是否可能,所以在這裏糾正我。這裏是我試圖實現,但沒有成功的代碼..引用指向字符數組的指針,一個strtok工作示例

#include <stdio.h> 
    #include <string.h> 
    #include <stdlib.h> 

      char *cPayload2[PARAMS]; 

    void ReadIn2(char *input) 
    { 
     //Initialize the pointer to the 
     char *PayloadPtr; 
     //start the parse 
     char *token = strtok(input, "#"); 
     //pointer to an array of strings(pointers to character arrays) 
     PayloadPtr = &cPayload2[0]; 

     while(token != NULL) 
     { 

這是有問題的部分,我可以改變我的全局數組的索引與這樣的條款。看來我不能用這個打印出有效載荷數組。

  *PayloadPtr = token; 
      //increment the index that the ptr refrences 
      PayloadPtr++; 
      //tokenize again 
      token = strtok(NULL, "#"); 
     } 

    } 



    int main(void) 
    { 

     char input[] = "jsiUjd3762BNK==#KOIDKKkdkdwos=="; 

     ReadIn2(input); 

此打印輸出bunked出於某種原因

 printf("%s\n",cPayload2[0]); 
     printf("%s\n",cPayload2[1]); 

     return 0; 
    } 

任何提示將大大appriciated。

+0

這看起來不太正確'* PayloadPtr = token;'因爲兩個變量的類型都是'char *',而您正在解除引用'PayloadPtr' – mathematician1975 2012-07-12 19:26:17

回答

1
char *PayloadPtr; 

應該

char **PayloadPtr; 

除此之外,你的代碼是正常的。

+0

+1完全錯過了這個解決方案。 – hmjd 2012-07-12 19:35:44

+0

謝謝SIR,工作完美。這仍然讓我在概念上有點混亂,但我想這是隨着時間和經驗而來的。 – Recurrsion 2012-07-12 19:46:13

+0

@Recurrsion我認爲這只是一個錯字,因爲其餘的代碼完全按照預期工作。你應該提高編譯器的警告級別,這會告訴你有關不兼容的任務。 – 2012-07-12 19:56:30

相關問題