简体   繁体   English

返回一个指向 float 的指针会在它到达 main 函数时改变地址

[英]Returning a pointer to float changes the address by the time it reaches main function

MAIN METHOD主要方法

 int x, y;
    printf("Please enter 2 integers separated by a space: ");
    scanf("%d %d", &x, &y);

OTHER METHOD.其他方法。 This is part of the matrix_get function called from the main function这是从主函数调用的 matrix_get 函数的一部分

if (key_comp (key, node->key) == 0){
       data_print(node->data);

SOME HEADER FILE一些头文件

typedef float Data_Item;

Ok so when I return the pointer to the Data_Item (it's a float typedef), the address of it changes and so when I dereference it in the main method it becomes null.好的,所以当我返回指向 Data_Item 的指针(它是一个浮点类型定义)时,它的地址发生了变化,因此当我在 main 方法中取消引用它时,它变为空。 Why?为什么?

printf("%d", &pdata);

should be应该

printf("%f", *pdata);

You're trying to be print the address of the pointer instead of the value of the pointer.您正在尝试打印指针的地址而不是指针的值。 Trying to print the address with %d is undefined.尝试用%d打印地址是未定义的。 Use %f for float.使用%f进行浮动。 Using the wrong format specifier invokes undefined behaviour .使用错误的格式说明符会调用未定义的行为

The memory you allocated for the pointer gets leaked, since the pointer's value is overwritten by a local variable's address.您为指针分配的内存会泄漏,因为指针的值被局部变量的地址覆盖。 Instead you should copy the data in the local variable into the memory allocated for the pointer.相反,您应该将局部变量中的数据复制到为指针分配的内存中。

*pdata = node->data;

The line线

   pdata=&(node->data);

changes the value of pdata .更改pdata的值。 It is now different from the value returned by malloc .它现在与malloc返回的值不同。 The line that makes more sense, that you have commented out, is:您已注释掉的更有意义的行是:

   //*pdata=node->data;

In the first line, you are assigning pdata to be the address of node->data .在第一行中,您将pdata指定为node->data的地址。 In the commented out line, you were trying to set the value of what pdata points to by node->data .在注释掉的行中,您试图通过node->data设置pdata指向的值。

You are missing the return from two of the branches.你错过了两个分支的return

Change改变

if(key_comp (key, node->key) == -1){
      bs_tree_search_h(node->left, key);
}else if(key_comp (key, node->key) == 1){
      bs_tree_search_h(node->right, key);
}

to

if(key_comp (key, node->key) == -1){
      return bs_tree_search_h(node->left, key);
}else if(key_comp (key, node->key) == 1){
      return bs_tree_search_h(node->right, key);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM