2017-02-19 211 views
2

我写下了接受用逗号分隔的群体值的代码。然后,我分割输入的字符串并将其存储到数组中。现在,我想存储一个双倍的数据,所以我可以在其上执行数学函数。但首先,我想输出它为双。我曾尝试的strtod,但它给我的如何将指针转换为C中的double?

passing argument 1 of '__strtod' makes pointer from integer without a cast [-  Wint-conversion] 

错误这是我的主要功能

int main(int argc, char const *argv[]) 
{ 
    int p_size, s_size; 
    int n =0; 
    char *population; 
    char population_string[100]; 
    printf("Enter the population size:"); 
    scanf("%d",&p_size); 
    printf("Enter the sample size:"); 
    scanf("%d",&s_size); 
    printf("Enter the population values separated by comma(,):"); 
    scanf("%s",&population_string); 
    printf("The population are:%s\n",population_string); 
    population = splitPopulation(population_string,p_size); 
    printf("The contents are:\n"); 
    for (int i = 0; i < p_size; i++) 
    { 
    printf("%c\n",population[i]); 
    printf("%f\n", strtod(population[i],NULL)); 
    } 
    return 0; 
} 

,这是我的分裂字符串

char * splitPopulation(char *population_string, int size){ 
    char *population_array=malloc(sizeof(char*)*size); 
    char *token = strtok(population_string,","); 
    for (int i = 0; i < size; i++) 
    { 
    population_array[i]= *token; 
    token= strtok(NULL,","); 
    } 
    return population_array; 
} 
功能

我的样品输入是:

Enter the population size:4 
Enter the sample size:2 
Enter the population values separated by comma(,):1,2,3,4 

回答

1

让我们从splitPopulation反向工作。这个函数返回字符指针

char * 

,但你实际上是返回一个指针数组为char,这意味着该类型是:

char ** 

换句话说,返回值是一个指针,它指向的是另一个指针,它指向逗号分隔的总体字符串中第一个数字的第一个字符。

所以现在人口是char **而不是char *,而population [i]是char *而不是char,所以你可以把它传递给strtod。 (你看到关于传递一个int作为指针的警告,因为population [i]当前是一个char并且正在被提升为int。)

您还必须将population_array定义为char **。当分配population_array [i]时,只需将它分配给没有尊敬操作符的令牌。

+1

这解决了它。感谢您为我启发了一些关于char的指针。 – nairda29

-1

你这样做:

strtod(population[i],NULL) 

population[i]是单char这是ASCII一个数字。你并不需要一个功能单一的char从ACSII转换为整数:

double pop_num = population[i] - '0'; 

也就是说,“0”变为0,而“1”变为1等说明为何这样的一个ASCII表作品。

顺便说一句,你的malloc分配4-8倍以上的需要,因为它使用sizeof(char*)当你的元素实际上是char而不是char*

+0

OP想要将一串数字标记为一个字符串数组(换句话说,指向char的指针数组),而不是一个字符数组。将人口价值表示为单个ASCII字符是没有意义的,尤其是鉴于OP希望将其打印为双倍字符。 –

相关问题