C语言中copyString函数隐式声明错误求助
C语言链表代码错误排查:隐式函数声明问题
问题描述
我两天后即将参加C语言考试,编写了一段实现简单链表的代码,但反复遇到错误提示:implicit declaration of function 'copyString'。我已尝试调整函数的声明顺序,问题仍未解决,请问存在哪些错误?
德语问候:Liebe Grüße
代码
#include <stdio.h> #include <stdlib.h> #include <string.h> struct listen{ int id; int wert; char *namen; char *strasse; int plz; struct listen *next; }; typedef struct listen elem; elem *createElem(int id, int wert){ elem* newElem = (elem*)malloc(sizeof(elem)); if(newElem == NULL) printf("War nischt!"); newElem->id = id; newElem->wert = wert; newElem->namen = NULL; newElem->strasse = NULL; newElem->plz = 0; return newElem; } int stringLen(char* len){ int d=0; while(*len++) d++; return d; } char *createStr(char* st) { char* newSt; newSt = (char*)malloc(stringLen(st)+1); if(newSt == NULL) {printf("Fehler");}; copyString(st, newSt); return newSt; } void copyString(char *von, char *nach) { while(*von!='\0') { *nach=*von; *von++; *nach++; } *nach = '\0'; } elem* addToList(elem *list, int wert, char* namen, char* strasse, int plz) { elem* p = createElem(list->id, wert); p->namen = createStr(namen); p->strasse = createStr(strasse); p->plz = plz; list->id++; p->next = list->next; list->next = p; return list; } elem* createList(){ elem* liste = createElem(0, 0); return liste; } void PrintElem(Elem *E) { printf("ID: %d | Wert: %d | Name : %s | Strasse: %s | PLZ: %d", E->id, E->wert, E->namen, E->strasse, E->plz); } void printList(elem* list){ printf("Liste:"); while(list->next != NULL) { printElem(list->next); list = list->next; } } int main(){ elem* Liste01 = createList(); Liste01 = addToList(Liste01, 4, "Peter", "Lustigweg", 15834); printList(Liste01); return 0; }
错误分析与解决
1. copyString隐式声明问题
C语言要求函数在调用前必须被声明或定义。你的代码中createStr函数在copyString之前定义,当编译到createStr里的copyString(st, newSt);时,编译器还不知道copyString的存在,因此报隐式声明错误。
解决方法:
- 方法一:在
createStr函数之前添加copyString的函数原型声明:void copyString(char *von, char *nach); - 方法二:把
copyString的完整定义移到createStr函数的前面。
2. 大小写敏感导致的函数/类型不匹配
C语言对大小写严格敏感,你的代码存在两处大小写错误:
- 定义的打印元素函数是
PrintElem(首字母大写P),但在printList里调用的是printElem(首字母小写p),编译器会找不到这个函数。 PrintElem函数的参数类型是Elem *E(首字母大写E),但你typedef的结构体别名是elem(小写e),类型不匹配会导致编译错误。
解决方法:
统一大小写,修改后的打印函数如下:
void printElem(elem *E) { printf("ID: %d | Wert: %d | Name : %s | Strasse: %s | PLZ: %d\n", E->id, E->wert, E->namen, E->strasse, E->plz); }
同时确保printList里调用的是printElem(和定义一致)。
3. 其他潜在问题(非编译错误,但建议修复)
- 自定义的
stringLen函数功能和标准库strlen重复,直接替换为strlen(st)可减少出错概率。 - C语言中
malloc的返回值无需强制转换((char*)),强制转换可能掩盖头文件未正确包含的问题。 - 错误提示语句建议添加换行符
\n,避免输出内容混乱。 addToList未处理list为NULL的情况,若传入空链表会崩溃,建议添加NULL判断增强鲁棒性。
内容的提问来源于stack exchange,提问作者Niklas
相关产品推荐
相关产品推荐

