strncmp: bug comparing two character arrays

John W. Eaton jwe at octave.org
Mon Jan 12 22:44:48 CST 2009


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.

jwe


More information about the Bug-octave mailing list