作者Ygulu (咕噜)
看板C_and_CPP
标题[问题] C++的问题
时间Wed Feb 11 12:10:42 2009
#include <stdio.h>
#include <stdlib.h>
#include <string.h.>
class car
{
public:
int wheel;
int person;
char name[];
};
int main()
{
car truck, bus, taxi;
bus.wheel=6;
bus.person=40;
strcpy(bus.name, "公车");
truck.wheel=8;
truck.person=3;
strcpy(truck.name, "卡车");
taxi.wheel=4;
taxi.person=5;
strcpy(taxi.name, "计程车");
printf("%s有%d个轮子,可载%d人\n", bus.name, bus.wheel, bus.person);
printf("%s有%d个轮子,可载%d人\n", truck.name, truck.wheel, truck.person);
printf("%s有%d个轮子,可载%d人\n", taxi.name, taxi.wheel, taxi.person);
system("pause");
}
有2075488429个轮子,可载44712人
卡车有8个轮子,可载3人
计程车有4个轮子,可载5人
请按任意键继续 . . .
有2075488429个轮子,可载44712人
卡车有8个轮子,可载3人
计程车有4个轮子,可载5人
请按任意键继续 . . .
以上是执行结果:
红色那行有问题
而且我按任意键想结束
结果不会结束 反而再跑出一个执行结果
要按cmd视窗的x才能关掉视窗 orz
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.169.161.198
1F:→ Ygulu:我在想是不是又是一些蠢问题 但我找了好久 找不出来@@ 02/11 12:11
2F:→ blexx:你把字串用int输出... 02/11 12:15
3F:推 lachu:字元阵列的长度没给 给了以後就可以正常执行了 02/11 12:19
4F:→ lachu:不过我也不知道为什麽... 02/11 12:19
5F:→ fjm31714:本来就该给吧.... 02/11 12:22
6F:→ Ygulu:可是卡车跟计程车都正常耶@@ 02/11 12:23
7F:→ Ygulu:改好了 正常了 可是为什麽原本卡车跟计程车是正常的? 02/11 12:23
※ 编辑: Ygulu 来自: 118.169.161.198 (02/11 12:24)
8F:→ Ygulu:字元阵列长度设1也可以@@ 02/11 12:25
9F:推 ledia:设 1 还是可能会有问题的 02/11 13:20
10F:→ ledia:没问题是运气好有 padding 02/11 13:21
11F:→ ledia:计忆体个管理要小心, 公车会烂是因为被别的车碾过了 02/11 13:22
12F:→ ledia:别的车空间不够往後写写到公车的记忆体 02/11 13:23
13F:→ pponywong:char name[] 跟 char* name 好像一样 02/11 13:41
14F:→ pponywong:所以只有sizeof(void*) 大小 02/11 13:41
15F:→ pponywong:用 taxi.name = strdup("计程车"); 02/11 13:42
16F:→ pponywong:class 再加一个 dtor 去 safe delete name 02/11 13:43
17F:→ MOONRAKER:如果是 bus.name = "公车" 就会对了吧 02/11 14:09
18F:→ MOONRAKER:不过这是不好的做法("公车"字串常数位址直接送给物件) 02/11 14:10
19F:推 interpreter:我觉得你是在写C 不是写C++ 02/12 18:53