数组比较中的意外行为 [英] Unexpected behavior in array comparison

查看:72
本文介绍了数组比较中的意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较表示矩阵的2D数组中的数据. 因为它是一个稀疏矩阵,所以我创建了2D数组compactMatrix,该数组具有行和列,其中值矩阵的入口不为null.

I'm trying to compare data in a 2D array that represents a matrix. As it is a sparse matrix, I created the 2D array compactMatrix, that has the lines and columns where the value matrix entrance is not null.

我正在使用此代码进行比较:

I'm using this code to make the comparison:

    if(compactMatrix[0][i] == compactMatrix[1][k] &&
       compactMatrix[1][i] == compactMatrix[0][k]){

        Do stuff...
    }

ik是我在for循环中当前正在查看的索引. 众所周知,我调试了compactMatrix[0][i]compactMatrix[1][k]以及compactMatrix[1][i]compactMatrix[0][k]的值确实相等.

Where i and k are the indexes I'm currently looking at in a forloop. For you to know, I debugged and the value of compactMatrix[0][i] and compactMatrix[1][k]and compactMatrix[1][i] and compactMatrix[0][k] were indeed equal.

试图使用来打印值

    j = compactMatrix[0][i];
    l = compactMatrix[1][i];
    printf("%i %i", &j, &l);

但是我想它给了我指针地址.

but it gives me the pointer address, I guess.

所以,我想知道为什么它在该if子句中返回false以及如何正确修复它.

So, I want to know why is it returning false in that if clause and how to fix it properly.

推荐答案

printf仅用于输出不需要地址的值.同样,当您尝试以整数格式打印地址时,它的行为未定义.该标准要求您使用%p打印地址.

printf is used for just outputting the value it doesn't need an address. Also when you try to print an address in integral formats its an undefined behaviour . The standard requires that you print address with %p.

贝Pe铭在评论中提到,您可能需要的是:

As CS Pei mentioned in the comments What you need probably is this:

printf ("%i %i",j,l);// you can use %d and %i interchangeably.

从标准本身来看有关%p的一些额外说明:

Some extra note about %p from the standard itself :

相应的参数应为指向void的指针. 输入项将转换为指针值 实现定义的方式.如果输入项是转换后的值 在同一程序执行的早期,所产生的指针 应等于该值;否则%p的行为 转换是不确定的.

The corresponding argument shall be a pointer to apointer to void. The input item is converted to a pointer value in an implementation-defined manner. If the input item is a value converted earlier during the same program execution, the pointer that results shall compare equal to that value; otherwise the behavior of the %p conversion is undefined.

因此,如果您确实使用p指定符,请不要忘记将参数强制转换为void*

So if you do use p specifier don't forget to cast the argument to void*

这篇关于数组比较中的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆