0

I have a function in C that is supposed to find how many 'X' are in a given char array. I receive the array in the argument, but i do not receive its length

So in C it would be

countX(char ss[]){
   int i=0; cont=0;
   while(ss[i]!='/0'){
      if(ss[i]=='X') cont++;
      i++;
   }
   return cont;
   }
}

I have to implement this in asssembly but since i do not have the length of the array, i do not know what value do i need to compare in cmp instruction to reach the end of the char array?

  • 2
    `'/0'` looks like a typo. Should be `'\0'` for the NUL terminating character which also denotes the end. That assumes you are dealing with C strings – Michael Petch Jul 07 '18 at 00:28
  • 2
    Character arrays in C don't automatically terminate with '\0', so I'm not sure that's a good comparison. – David Wohlferd Jul 07 '18 at 00:28
  • Thank you for your comments, and I did notice it was incorrect, it should be '\0'. Even though I agree with you, that code was given in a class exercise, so I will have to deal with it, no matter the circumstances. – Luís Ornelas Jul 07 '18 at 00:53
  • If the code you posted was given to you by your lecturer then the typo would need to be fixed. The code suggests that the array is NUL (0) terminated. You will have to scan for both the value 0 (end of the string) and for the letter 'X'. – Michael Petch Jul 07 '18 at 02:01
  • @DavidWohlferd If they represent strings, that's a perfectly valid assumption to make. – fuz Jul 07 '18 at 09:10
  • Note that you can easily implement this function using `rep scasb`. – fuz Jul 07 '18 at 09:11

1 Answers1

0

This function is called strlen. It's a search for the first 0 byte.

It only works if the array ends with a terminating 0 byte, i.e. it's an implicit-length C string.

There's no magic here, just loop until you find a 0 byte.

This is why strlen is slow compared to explicit-length strings that are pointer+length. (Real libc implementations of strlen are optimized with hand-written asm to check 16 or 32 bytes at once, though. See Questions about the performance of different implementations of strlen, and Is it safe to read past the end of a buffer within the same page on x86 and x64?).


For things other than strings, it's much more common to pass a pointer+length to a function, e.g. void foo(float *arr, size_t len);.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847