2017-02-19 215 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希望將其打印爲雙倍字符。 –

相關問題