strncmp: bug comparing two character arrays
Thorsten Meyer
thorsten.meyier at gmx.de
Sun Jan 18 15:24:08 CST 2009
Hi,
John W. Eaton wrote:
> On 1-Jan-2009, Thorsten Meyer wrote:
>
> | Hi,
> |
> | while patching the bug just reported I found another one in octave mercurial:
> |
> | octave:56> strncmp(["ab";"cd"], ["ab";"ce"], 2)
> | ans = 1
> | octave:57> strncmp(["ab";"cd"], ["ab";"ce"], 3)
> | ans = 1
> | octave:58> strncmp(["ab";"cd"], ["ab";"ce"], 4)
> | ans = 0
> |
> | The relevant part of the source code in src/strfns.cc is here:
> |
> | for (int i = 0; i < n; i++)
> | {
> | if (s1(i) != s2(i))
> | {
> | retval = false;
> | return retval;
> | }
> | }
> |
> | retval = true;
> |
> | So strncmp compares the first n elements of the complete character array and not the first n
> | elements of each string in the character array.
>
> | I can probably provide a patch for the 2d-case. But what should the function do in case of two n
> | dimensional character arrays with n>2 (and how do I index into an n-d array?)?
>
> Do the N-d arrays have the same dimensions? Or at least the same
> number of elements? Probably all you need to do is iterate over all
> the elements. Then you can use a single index.
>
As Ben pointed out, compatible behaviour is to compare the first n chars
of the array (in the internal representation). The octave function
strncmp does this already even for the n-d case.
regards
Thorsten
More information about the Bug-octave
mailing list