简体   繁体   English

从数组打印字符串打印错误的结果

[英]Printing string from array prints wrong result

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: recCount 并不重要,但本质上,当我这样做时,我尝试了这个:

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

Yet for some reason, the output is this:然而由于某种原因,output 是这样的:

ðy
test

Anyone know why?有谁知道为什么?

Edit: @MikeCAT My node setup is as follows:编辑:@MikeCAT 我的节点设置如下:

    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.我要么得到一些随机字符,(null),要么只是一个空行。

The expression recCount++ is add one to recCount and evaluated to the value of recCount before the addition .表达式recCount++recCount加一,并在加法之前计算为recCount的值。

Therefore, you should use indexArray[recCount-1] instead of indexArray[recCount] to get the assigned value after that.因此,您应该使用indexArray[recCount-1]而不是indexArray[recCount]来获取之后的分配值。

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);

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

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