gpt4 book ai didi

c - 赋值给数组类型为 ch= ch+(s[i]) 的表达式;

转载 作者:太空宇宙 更新时间:2023-11-04 03:09:31 27 4
gpt4 key购买 nike

我无法将字符指针数组 s 的字符存储到字符数组 ch 中:

    int main() {
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
char ch[50];
int i;
s=s+' ';
for(i=0;i<=strlen(s)+1;i++)
{
if(s[i]!=' ')
{
ch= ch+(s[i]);
}
else
{
printf("%c \n",ch);
ch=' ';
}
}
return 0;
}

这是错误信息:

 error: assignment to expression with array type
ch= ch+(s[i]);
^
Solution.c:27:15: error: assignment to expression with array type
ch=' ';

最佳答案

对于初学者来说,这个循环

for(i=0;i<=strlen(s)+1;i++)

当 i 等于 strlen(s)+1 时调用未定义的行为,因为试图访问超出动态分配数组的内存。

这些陈述

ch= ch+(s[i]);

ch=' ';

没有意义。数组没有运算符 +,它们是不可修改的左值。

for 循环不适合这样的任务,因为在循环中不会输出最后一个单词。

你的意思是下面的。

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

int main(void)
{
char *s;
s = malloc(1024 * sizeof( char ) );

scanf("%1023[^\n]", s);
s = realloc(s, strlen(s) + 1);


char ch[50] = { '\0' };

size_t i = 0, j = 0;

do
{
if ( s[i] != ' ' && s[i] != '\t' && s[i] != '\0' )
{
ch[j++] = s[i];
}
else if ( ch[0] != '\0' )
{
ch[j] = '\0';
puts( ch );
j = 0;
ch[j] = '\0';
}
} while ( s[i++] != '\0' );

return 0;
}

如果进入

Hello muskan litw

那么程序输出将是

Hello
muskan
litw

关于c - 赋值给数组类型为 ch= ch+(s[i]) 的表达式;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57991968/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com