【发布时间】:2015-02-24 17:11:47
【问题描述】:
我试图通过在函数之间传递一个指向字符串的指针,在每种情况下将不同的错误消息分配给错误变量,但由于任何原因都不能正常工作。
代码如下:
//This function takes a pointer to a char.
int lee(Fecha *f, char *error){
int checking;
printf("Introduzca una fecha compuesta por día, mes, y año\n");
checking = scanf("%i %i %i", &f->day, &f->month, &f->year);
printf("%d\n", checking);
switch (checking){
case 0:
//The message is assigned to the space where error points to.
*error = "Formato de fecha incorrecto. El día debe ser un entero.";
break;
case 1:
*error = "Formato de fecha incorrecto. El mes debe ser un entero.";
break;
case 2:
*error = "Formato de fecha incorrecto. El año debe ser un entero.";
break;
}
return (checking == 3);
}
int main(){
Fecha f;
//error is declared like a pointer
char * error;
int ret;
//The pointer is passed to the function as argument.
ret = lee(&f, error);
printf("%s", error);
return 0;
}
还有输出:
user@console:~/$ ./Sesion1
Introduzca una fecha compuesta por día, mes, y año (o 0 0 0 para terminar el programa)
23 dfgadkfhgsñdgh 5
1
Segmentation fault
【问题讨论】:
-
看看
*error并思考这意味着什么。你给它分配了什么?它是如何记忆的? -
是的.. 寻找 malloc 的错误.... 失败....
标签: c function pointers arguments