c语言中 结构体中数组赋值问题

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

typedef struct hui{
char *data;
int top;
} *Hui;

int IsHui(char *s);

void main() {
char c[100];
printf("Enter:\n");
gets(c);
if(IsHui(c))
printf("Is\n");
else
printf("NO\n");
}

int IsHui(char *s) {
int n = strlen(s);
Hui S = (Hui)malloc((n/2)*sizeof(char)+sizeof(int));
S->top = -1;

for(int i = 0; i < n/2; i++) {
S->top++;
S->data[i] = s[i];//这一步使程序停止????为什么???

}
char temp;
i = i - 1;
while(S->top>=0) {
temp = S->data[i];
if(temp != s[n-i-1])
return 0;
i--;S->top--;
}
return 1;
}

这是我的回文游戏.为什么S->data[i] = s[i];这一步对结构体中的数组赋值运行不了???晕~~~

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

typedef struct hui{
char data[20]; //你写的是指针,要开数组的话必须用malloc开空间,我是
//用直接改为数组了。
int top;
} *Hui;

int IsHui(char *s);

void main() {
char c[100];
printf("Enter:\n");
gets(c);
if(IsHui(c))
printf("Is\n");
else
printf("NO\n");
}

int IsHui(char *s) {
int n = strlen(s);
Hui S = (Hui)malloc((n/2)*sizeof(char)+sizeof(int));
S->top = -1;

for(int i = 0; i < n/2; i++) {
S->top++;
S->data[i] = s[i];//这一步使程序停止????为什么???

}
char temp;
i = i - 1;
while(S->top>=0) {
temp = S->data[i];
if(temp != s[n-i-1])
return 0;
i--;S->top--;
}
return 1;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-11-15
  相同类型的结构体是可以直接赋值的,这是ANSI/ISO C规定的。ANSI/ISO C规定的合法行为,编译器是必须支持的。

但不能进行比较,例如
if (stu[1] == stu[2])是不允许的。

这种问题不能靠试验获得准确的答案,因为你用的编译器支持并不表明其他编译器也支持。
第2个回答  2008-10-29
以前也回答过这样的问题
S->data[i] = s[i];//没有初始化S->data,就想访问*(S->data+i),当然不可以,提到循环外改为S->data = s;这就对初始化了
你搜索下"数组与指针",网络上有关于这方面的讨论,
当然,除此之外,还有其他问题,建议还是重写吧!

参考资料:http://zhidao.baidu.com/question/72810782.html

第3个回答  2008-10-29
typedef struct hui{
char data[10];
int top;
} *Hui;

char *data;改成这样char data[10];就好了

这是因为没有为data分配足够空间