2016-03-08 130 views
1

我想從用戶的輸入,我沒有確切的輸入長度,所以我使用malloc,我分裂他們之間的空間字符並且只需要打印一個數組,但我得到警告,即賦值時將指針整數,未在下面一行鑄造:在C:鑄造警告在C:賦值整數從指針沒有鑄造

array[i++] = p; 

和我的整個程序如下:

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

int main() 
{ 
    char buf[] ="abc qwe ccd"; 
    int i; 
    char *p; 
    char *array=malloc(sizeof(char)); 
    i = 0; 
    p = strtok (buf," "); 
    while (p != NULL) 
    { 
    array[i++] = p; 
    p = strtok (NULL, " "); 
    } 
    for (i=0;i<3; ++i) 
    printf("%s\n", array[i]); 
    return 0; 
} 

人請告訴我我的代碼有什麼問題。 謝謝。

回答

3

以下作業不正確。

array[i++] = p; 

array[i++]的計算結果爲鍵入charp的類型是char*

這就是編譯器所抱怨的。 通過您使用的方式來判斷array,它需要是char**類型。

char **array = malloc(sizeof(*array)*20); // Make it large enough for your needs. 
+0

Thanx alot。指針總是殺了我:( –

+0

@BASEERHAIDER,不客氣,需要一點時間才能適應。 –

2

我想你想創建的指針數組char代替的char陣列。

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

int main (void) 
{ 
    char buf[] ="abc qwe ccd"; 
    int i; 
    char *p; 
    /* change type of array from char* to char** */ 
    char **array=malloc(sizeof(char*) * sizeof(buf)); /* allocate enough memory */ 
    i = 0; 
    p = strtok (buf," "); 
    while (p != NULL) 
    { 
    array[i++] = p; 
    p = strtok (NULL, " "); 
    } 
    for (i=0;i<3; ++i) 
    printf("%s\n", array[i]); 
    free(array); /* it is good to free whatever you allocated */ 
    return 0; 
}