【发布时间】:2023-03-21 13:10:01
【问题描述】:
我在这方面花费了大量时间,最后终于让它工作了(因为它保存了值并打印它们)。我想按字母顺序对它进行排序。如果我将值添加到我的列表中,它们不会以我添加它们的相同顺序打印出来,但它似乎有点随机......似乎 strcpy 不像我想象的那样工作。 ..
#include <iostream>
#include <cstdlib>
#include <string.h>
#include <stdio.h>
using namespace std;
typedef struct list list_t;
struct list{
list *next;
char *nam;
int age;
};
static list_t *top = NULL;
void add_value(char * name1, int age){
list * neww = (list_t*)malloc(sizeof( list_t));
//tmp = top;
neww->age = age;
neww->nam = (char*)malloc(strlen(name1) + 1);
neww->next = NULL;
strcpy(neww->nam, name1);
list * tmp = (list_t*)malloc(sizeof(list_t));
tmp = top;
if (tmp==NULL){
top = neww;
//printf("%s\n", top->nam);
}else
while (1){
if (tmp->next == NULL){
tmp->next = neww;
break;
}
//printf("top - %s %d\n neww - %s %d\n tmp - %s %d", top->nam, top->age, neww->nam, neww->age, tmp->nam, tmp->age);
if (strcmp(neww->nam, tmp->nam)>=0){
neww->next = tmp->next;
tmp->next = neww;
break;
}
tmp = tmp->next;
}
}
void print(){
list * tmp = (struct list*)malloc(sizeof(struct list));
tmp = top;
while (tmp){
printf("%s %d\n", tmp->nam, tmp->age);
tmp = tmp->next;
}
}
int main(){
char namee[100];
int age;
for (int i = 0; i < 5; i++){
scanf("%s %d", &namee, &age);
add_value(namee, age);
}
print();
return 0;
}
【问题讨论】:
-
1:什么语言? 2:问题是什么?
-
也许您应该从了解
strcpy的实际工作原理开始。 -
你在
add_value中为tmp分配空间,然后立即覆盖指向那个空间的指针;我很确定这是不对的。 -
我删除了 C++ 标签,因为代码是纯 C 的,但有一个例外,
<iostream>的未使用包含。我把它留在原地是因为人们应该非常警惕改变问题的实质。这是错的吗? -
@Cheersandhth.-Alf:尽管有过时的习语,但如果代码是通过 C++ 编译器推送的(显然是这样),那么它就是 C++ ......这使得这是一个 C++ 问题。我已经把标签放回去了。