[英]Pointer error when trying to use “strcpy” in C to copy char elements from one array to another
What I am trying to do is check if the word entered by the user has first five alphabetical letters and if it has, I need to copy those letters to another array.But it gives me an error saying "passing argument 1 of strcpy makes pointer from integer without cast[enabled by default]". 我要执行的操作是检查用户输入的单词是否具有前五个字母,是否需要将这些字母复制到另一个数组。但这给我一个错误,提示“传递strcpy的参数1使指针从没有强制转换的整数[默认启用]”。
char s1[100];
char a1[100];
char alpha[5]={'a','b','c','d','e'};
int i,j,k=0;
printf("Enter a word");
fgets(s1,100,stdin);
for(i=0;i<strlen(s1);i++)
{
for(j=0;j<5;j++)
{
if(s1[i]==alpha[j])
{
strcpy(a1[k],s1[i]);
k++;
}
}
}
Need help to figure out what is wrong with this 需要帮助找出这是怎么回事
strcpy
has two input parameters char *
. strcpy
有两个输入参数char *
。 You can't use it for two characters. 您不能将其用于两个字符。 If you want to copy one character from one array to another then you need to use
= operator
as a1[k] = s1[i]
如果要将一个字符从一个数组复制到另一个数组,则需要使用
= operator
作为a1[k] = s1[i]
You only need one loop: 您只需要一个循环:
Replace char by char: 用char替换char:
for(i = 0; i < strlen(s1); i++)
{
a1[i] = s1[i];
}
Or, use strcpy like this: strcpy(a1, s1);
或者,像这样使用strcpy:
strcpy(a1, s1);
Answering your comment: 回答您的评论:
I tried a1[k]= s1[i] but it displays some vague characters for a1 ex-: if s1 is "abc" , a1 displays as "abc!"
我尝试了a1 [k] = s1 [i],但是它对a1 ex-显示了一些模糊的字符:如果s1是“ abc”,则a1显示为“ abc!”。
C strings need to be null terminated. C字符串需要以null终止。
Try doing this: 尝试这样做:
char s1[100] = {0};
char a1[100] = {0};
Small example: 小例子:
#include <string.h>
#include <stdio.h>
int main()
{
char s1[100] = {0};
char a1[100] = {0};
int i,j,k=0;
printf("Enter a word: ");
fgets(s1,100,stdin);
for(i = 0; i < strlen(s1); i++)
{
a1[i] = s1[i];
}
printf("a1 now contains: %s", a1);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.