2015-04-06 45 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