gpt4 book ai didi

c - 指针的内容在使用后消失

转载 作者:行者123 更新时间:2023-11-30 21:35:27 26 4
gpt4 key购买 nike

我有这段代码,其中 complexp是一个指向 struct 的指针代表一个复数。第一个printf命令工作正常并且 complexp的内容被打印。然而,第二个printf无法正常工作并打印 0两次(这是不正确的)。

这两行之间没有代码。

int main()
{
ComplexP complexp = (ComplexP) malloc(sizeof(ComplexP));
complexp = fromCharFunc(s);

printf("complexp: real: %f, imaginary: %f\n", complexp->real, complexp->imaginary);

printf("1complexp: real: %f, imaginary: %f\n", complexp->real, complexp->imaginary);

return 0;
}
typedef struct Complex {
double real;
double imaginary;
} Complex;

typedef struct Complex* ComplexP;
ComplexP fromCharFunc(char * s)
{
if(s == NULL)
{
return NULL;
}


char* sreal;
char* simaginary;
double real;
double imaginary;

char str [DEFAULT_SIZE];

strcpy(str, s);
sreal = strtok(str, REALL_PART_DELIMITER);

simaginary = strtok(NULL, IMAGINARY_PART_DELIMITER);

int len1 = strlen(sreal) + strlen(simaginary);
int len2 = strlen(s) - strlen(IMAGINARY_PART_DELIMITER);

int diff = len1 == len2 ? 0 : 1;


if(diff)
{
return NULL;
}


if(verifyIsNumber(sreal))
{
real = atof(sreal);
}
else
{
return NULL;
}

if(verifyIsNumber(simaginary))
{
imaginary = atof(simaginary);
}
else
{
return NULL;
}

Complex complex = {real, imaginary};
ComplexP complexp = &complex;

return complexp;

}
/**
* @brief determines whether a string represents a number
* @param char *s poiter to a string
* #retrun 0 if not a number, 1 if is a number
*/
int verifyIsNumber(char *s)
{
char c;
int i = 0;
while( *(s+i) != '\0')
{
c = *(s+i);
if ((c >= MIN_DIGIT && c <= MAX_DIGIT) || c == POINT || c == MINUS)
i++;
else
{
return 0;
}
}

return 1;

}

最佳答案

您正在返回一个指向局部变量的指针。该变量在作用域结束时被删除。您应该考虑返回 Complex 变量而不是 ComplexP

ComplexP fromCharFunc(char * s)
{

// ...

// This variable is deleted after the function ends
Complex complex = {real, imaginary};

// After deletion, this pointer points to invalid memory
ComplexP complexp = &complex;

return complexp;
}

您的第一个 printf 调用有效,因为 complex 中的值仍然恰好位于指针指向的内存位置。这是未定义的行为。使用不同的编译器或不同的系统,可能会导致两个 printf 命令都失败,或者都成功。

如果你想返回ComplexP,你应该使用malloc保留内存。

ComplexP fromCharFunc(char * s)
{

// ...

// Create a temporary variable
Complex complex = {real, imaginary};

// Reserve memory for your return variable
ComplexP complexp = malloc(sizeof(Complex));

// Copy your temporary variable to the reserved memory location
*complexp = complex;

return complexp;
}

关于c - 指针的内容在使用后消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33997013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com