-3

I am trying to print out values in integer pointer. This pointer stores binary search tree keys inorder way.

So my inorder function is,

int traversal(int* num,node *t, int i) {

    if (t == NULL) {
        return i;
    }
    if (t->left != NULL) {
        i = traversal(num, t->left, i);
    }
    num[i] = &(t->value);
    i++;
    if (t->right != NULL) {
        i = traversal(num, t->right, i);
    }
    return i;
}

And print function is,

void traversalPrint(int* nums) {
    for (int i = 0; nums[i] !='\0'; i++) {
        printf("%d", &nums[i]); 
    }

}

int main(){
    int* numPtr = (node*)malloc(sizeof(int*));
    node* bst = NULL:
    traversal(numPtr, bst, 0);
    traversalPrint(numPtr);
}

My issue is traversalPrint function prints out numPtr's memory address, not value. How can I print out pointer's value? Thanks in advance!

jayko03
  • 2,329
  • 7
  • 28
  • 51

2 Answers2

1

The issue concerning "printing addresses" is that with printf("%d", &nums[i]), you actually take the address of "something". Note that &anObject gives you the memory address of anObject, and &nums[i] gives the memory address of nums[i] (which is the address of the i'th element of nums). BTW: %d is the wrong format specifier for pointer values, and you actually yield undefined behaviour by doing so.

For printing the integral value, use printf("%d", nums[i]) instead.

Note further that the code in your main function does not allocate anything for nums, such that your program will write to non-initialized memory and will again yield undefined behaviour.

use at least int* numPtr = calloc(MAXNODES, sizeof(int)) instead, thereby making sure that every entry is initialized with 0. Otherwise, your comparison in nums[i] !='\0' (which, BTW, should be written as nums[i] != 0) will probably fail, again leading to UB later on.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • I edited `numPtr` as `numPtr = (node*)malloc(sizeof(int));` and tried. but does not have any luck. Then I changed it as you described `numPtr=calloc(sizeof(node*), sizeof(int));` but not luck as well. Is `MAXNODES` same as sizeof(node*) or do you mean something different? – jayko03 Oct 02 '17 at 03:21
0

Try nums[i] instead of &nums[i].

frslm
  • 2,969
  • 3
  • 13
  • 26