我无法将字符指针数组的字符存储到字符数组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=' ';发布于 2019-09-18 12:10:14
您的代码中有许多错误(其中一些在注释中指出)。下面是一个可行的解决方案,它可以实现我认为的您正在寻找的东西:
#include <stdio.h>
#include <stdlib.h>
int main() {
char* s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 2); // Add 2 because you later append a space!
//Write your logic to print the tokens of the sentence here.
//i
char ch[50] = { '\0' }; // Make sure you initialise the buffer!
int i;
// s = s + ' '; // This doesn't do what you think - it's adding the value of ' ' to the string's address!
strcat(s, " "); // This appends a blank to the string!
for (i = 0; i < strlen(s); i++) // For 7 chars, will do [0] thru [6]!
{
if (s[i] != ' ')
{
// ch = ch + (s[i]); // You can't just 'add; an element to an array!
ch[i] = s[i];
}
else
{
// printf("%c \n", ch);
printf("%s \n", ch); // Use this to print the entire ch string so far!
ch[i] = ' ';
}
}
return 0;
}我已经在修改了您的代码的地方发表了评论,您可以随意要求进一步解释!
发布于 2019-09-18 12:14:52
首先,这个循环
for(i=0;i<=strlen(s)+1;i++)当我等于strlen(s)+1时,会调用未定义的行为,因为有人试图访问动态分配数组之外的内存。
这些陈述
ch= ch+(s[i]);和
ch=' ';别说得通。数组没有运算符+,它们是不可修改的lvalue。
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
litwhttps://stackoverflow.com/questions/57991968
复制相似问题