2016-03-08 97 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; 
}