2015-04-06 29 views
-1

我想隨機化我的字符串,所以這是我的代碼。如何將char傳入函數?

while(strcmp(word,"END")!=0) 
{ 
printf("Enter word"); 
fgets(input,sizeof(input),stdin); 
sscanf(input,"VERTEX %s",key1); 
strcpy(list[count],key1); 
count++; 
} 
random(list); 

我申報清單,並作爲KEY1 char list[32],key1[32]; 然後我試圖將它傳遞給這個函數

void random(char* list) 
{ 
    int i = rand()%5; 
    char key1[32]; 
    printf("%d",i); 
    printf("%s",list[i]); 
    strcpy(key1,list[i]); 
} 

,但它給了我這個警告

incompatible integer to pointer conversion passing 'char' 
    to parameter of type 'char *' 

,它不能打印。任何建議?

+0

編譯器會告訴你這個問題:'不兼容的整數指針轉換過客「字符」,以類型的參數「字符*」'下一次嘗試搜索那個錯誤 – ZivS 2015-04-06 10:08:07

+0

'char list [32];' - >'char list [5] [32];''和'void random(char * list)' - >'void random(char list [] [32]) ' – BLUEPIXY 2015-04-06 10:25:02

回答

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

void random(char list[][32], char *key, int size){ 
    int i = rand()%size; 
    printf("choice %d\n",i); 
    printf("choice key is %s\n", list[i]); 
    strcpy(key, list[i]); 
} 

int main(void){ 
    char list[5][32], key1[32], word[32]; 
    int count = 0; 
    srand(time(NULL)); 

    while(1){ 
     printf("Enter word : "); 
     fgets(word, sizeof(word), stdin); 
     if(strcmp(word, "END\n")==0) 
      break; 
     if(count < 5 && 1==sscanf(word, "VERTEX %s", key1)){ 
      strcpy(list[count++],key1); 
     } 
    } 
    if(count){//guard for count == 0 
     random(list, key1, count); 
     printf("choice key : %s\n", key1); 
    } 

    return 0; 
} 
+0

它在運行這段代碼時有錯誤。它有浮點異常@BLUEPIXY – asiandudeCom 2015-04-06 10:54:45

+0

@asiandudeCom它對我很好。 [DEMO](http://ideone.com/qskZbZ)您有任何意見嗎?順便說一下,**我不使用浮點數。** – BLUEPIXY 2015-04-06 11:00:31

+0

我輸入了約3個字,然後浮點錯誤出現@BLUEPIXY – asiandudeCom 2015-04-06 11:09:03

0

如果你定義char list[32];,callled random(list);和使用void random(char* list),然後

strcpy(list[count],key1); 
    printf("%s",list[i]); 
    strcpy(key1,list[i]); 

所有語句都是錯誤的。

在你的代碼,list[count]list[i]的類型char,不const char *char *的,按要求。

+0

我想將key1複製到數組中,而不是將副本列表[i]複製到key1中。 @Sourav Ghosh – asiandudeCom 2015-04-06 10:09:14

+0

@asiandudeCom更新了我的答案,添加了一些更多的說明。請檢查。 – 2015-04-06 10:22:15

+0

你是什麼意思未初始化我已經宣佈它@Sourav Ghosh – asiandudeCom 2015-04-06 10:22:15

0
void random(char *list); 

所以這裏listchar類型的指針,當你通過一個有效的字符數組,這個API列表,然後指向您的陣列list

現在你所需要的僅僅是

printf("%s",list); /* Format specifier %s needs char * */ 
    strcpy(key1,list); /* The arguments should be char * */ 
+0

我在while循環中使用strcpy錯誤嗎?我想將已經sscanf的key1複製到數組中。 @Gopi – asiandudeCom 2015-04-06 10:23:27

+0

@asiandudeCom如果你想存儲多個字符串,那麼你應該有一個2D字符數組或char指針數組。所以是的,你在while循環中做的是錯誤的。 Chage列表到'list [32] [100];'並確保你的char *'而不是'char'到API的 – Gopi 2015-04-06 10:27:36

相關問題