0

Hey I was wondering if I could get some help on this. I have an array that was given to me like this:

char **indexArray;

And I was told to add to the array like this:

indexArray[recCount++]=root->data;

recCount isn't important, but essentially, when I do this, I tried this:

printf(indexArray[recCount]);
printf(root->data); 

Yet for some reason, the output is this:

ðy
test

Anyone know why?

Edit: @MikeCAT My node setup is as follows:

    numNodes += 1;

    struct bNode *node = (bNode *) malloc(sizeof(bNode));
    node->data = data;
    node->left  = NULL;
    node->right = NULL;
    printf(node->data); #prints the data I want so this works just fine
    return node;
}

Then I do something along the lines of:

bNode root = makeNode("test")

then I do this:

indexArray[recCount++]=root->data;

Yet when I do this:

printf("%s", indexArray[0]);

I either get some random character, (null), or just a blank line.

1 Answer 1

1

The expression recCount++ is add one to recCount and evaluated to the value of recCount before the addition.

Therefore, you should use indexArray[recCount-1] instead of indexArray[recCount] to get the assigned value after that.

Also

printf(indexArray[recCount]);
printf(root->data); 

looks dangerous because it will interpret % in the data as format specifier and invoke undefined behavior because there are not data corresponding to the specifiers if it is included.

It should be

printf("%s", indexArray[recCount]);
printf("%s", root->data);

or

fputs(indexArray[recCount], stdout);
fputs(root->data, stdout);
Sign up to request clarification or add additional context in comments.

2 Comments

My node setup is as follows: struct bNode *makeNode(char *data) { numNodes += 1; struct bNode *node = (bNode *) malloc(sizeof(bNode)); node->data = data; node->left = NULL; node->right = NULL; printf(node->data); #prints the data I want so this works just fine return node; } Then I do something along the lines of: bNode root = makeNode("test") then I do this: indexArray[recCount++]=root->data; Yet when I do this: printf("%s", indexArray[0]); I either get some random character, (null), or just a blank line.
any ideas of how to fix this please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.