字符串指针在函数之间不起作用

string pointers not working between functions

我试图通过在函数之间传递指向字符串的指针来为每种情况下的错误变量分配不同的错误消息,但由于某种原因无法正常工作。

代码如下:

//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

您需要传递一个指向函数输出参数的指针。因为你的输出参数是char*,指向它的指针是char**

要修复,请将相应的行更改为:

int lee(Fecha *f, char **error);
// ...
ret = lee(&f, &error);

由于要输出到字符串,需要将指针传递给 char*,因此需要将错误作为 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;
}

此外,您应该考虑不要像在 main() 中处理 char* 错误那样在声明后留下没有值的指针。

问题是,当您有一个未初始化的指针然后您忘记给它一个值或类似的东西时,它可以指向您的应用程序内存中的任何位置(或超出它)。虚拟内存保护您不读写其他应用程序的内存(一般来说),但您可能会遇到指针恰好指向应用程序内的某些数据的情况。如果您随后使用此指针进行写入或读取,您将得到不可预知的结果,从仅显示错误数据到损坏数据或崩溃应用程序,这显然是您不希望的。