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

11
  • The & in &nums[i] gives you back the memory address. It's only needed for strings. Commented Oct 1, 2017 at 19:41
  • @0decimal0 any reason you don't vote to close as duplicate and just put a comment? Commented Oct 1, 2017 at 19:41
  • @bolov My privileges I guess. Commented Oct 1, 2017 at 19:42
  • @0decimal0 what does that mean? Commented Oct 1, 2017 at 19:43
  • @bolov Close voting access begins at 5k rep. Commented Oct 1, 2017 at 19:43

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.