gpt4 book ai didi

c - printf 改变内存值

转载 作者:行者123 更新时间:2023-12-04 10:12:50 25 4
gpt4 key购买 nike

我正在尝试做一些定点 vector 数学运算,似乎无论何时我打印任何东西,似乎都无关紧要。我的 vector 值发生变化。代码是使用 Zilog 的 ZDSII 开发人员工作室编译的。

我有一个这样定义的结构

typedef struct {
long x;
long y;
} vector;

结构中的值在函数中初始化

void initVector( vector * vec, int x, int y ) {
vec -> x = (long) x << 14;
vec -> y = (long) y << 14;
}

在我的主要功能中我有

int main() {
vector * vector1;

initVector( vector1, 1, 2 );
printf( "foo" ); // this prints alright
printf( "%d , %d", vector1 -> x >> 14, vector1 -> y >> 14 ); //garbage
...

...
}

打印垃圾。这些值将根据我实际打印值的 printf 之前的 printf 语句的数量而改变。

最佳答案

您使用未初始化的vector1

vector * vector1;

initVector( vector1, 1, 2 );

因此 initVector 调用未定义的行为。

成功

vector vector1;
initVector(&vector1, 1, 2);

vector * vector1 = malloc(sizeof *vector1);

关于c - printf 改变内存值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17064215/

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