【发布时间】:2013-03-31 12:51:37
【问题描述】:
我在 struct 中输入字符串指针时遇到问题。这是我的代码:
typedef struct{
char *name;
int age;
}stu;
void allocate(stu* &s, int n){
s = (stu*) malloc(n * sizeof(stu));
if(s == NULL){
printf("\nNot enought memory!");
exit(1);
}
}
// Input info
void input_info(stu* &s, int n){
void input(stu &s); //prototype
for(int i = 0; i < n; i++){
printf("\n-- Student #%d:", i+1);
input(*(s+i));
}
}
void input(stu &s){
fflush(stdin);
printf("\nEnter student's name: ");
gets(s.name);
printf("\nEnter student's age: ");
scanf("%d", &s.age);
}
// End input
//Output info
void output_info(stu* s, int n){
void output(stu s); //prototype
for(int i = 0; i < n; i++){
printf("\n-- Student #%d:", i+1);
output(*(s+i));
}
}
void output(stu s){
printf("\nName: %s", s.name);
printf("\nAge: %d", s.age);
}
//End output
int main(){
stu* s;
int n;
printf("How many students you want to input?: ");
scanf("%d", &n);
allocate(s, n);
input_info(s, n);
output_info(s, n);
getch();
}
当我输入第二个学生的名字时,它被打破了?我分配了内存。我想问一下如何为stu指针释放内存?感谢阅读
【问题讨论】:
-
Read a book,因为这不是正确的 C++ 代码。使用 std::string,永远不要碰 malloc,删除所有指针和动态分配,不要使用 stdio。
-
你应该分配给
name -
往伤口里加盐..
fflush(stdin);标准未定义。 -
对我来说最奇怪的部分是在这种混乱中,他实际上正确使用了引用指针参数(尽管他的股票随着随后的
malloc()而立即下跌)。我认识一些在这个概念上苦苦挣扎的专业工程师,他只是走上前标记它=P -
看到
gets()了吗?那东西太邪恶了,它已被弃用,并且不会在该语言的下一个版本中出现。想想它在做什么,它在哪里把它应该得到的数据,以及如何通过使用std::string、std::getline()并抛弃malloc()来避免这种混乱new.