1

I'm writing a function for my arduino program that takes a character array of any size and will mark all the characters that aren't in the alphabet by changing their value to '1'.

I have a switch variable (foundSym) that will turn to 0 if the character IS part of the alphabet. At the end of my first for loop if the switch never changed, that means the character was NOT a letter and will be marked. Note I also don't want to mark space characters (' ').

The issue I have is every array I pass into the function will only have a length of 4, no matter the size.

I've checked the length of each array before it enters the function and when it is in the function, everytime the size gets shortened to 4 elements!

Here is my function...what am I doing wrong??

void markSymbols(char str[]){
  for(int i = 0; i<sizeof(str); i++){
    int foundSym = 1;
    for (int j = 0; j<26; j++){
      if (str[i] == alphabet[j]) {
        foundSym = 0; 
        break;
        }
    }
    if (str[i] == ' ') foundSym = 0;
    if (foundSym == 1) str[i] = '1';
  }

}
2
  • Daft question but why not use the isAlpha function? Sep 29 '16 at 12:13
  • Or isAlpha doesn't give the correct set of characters check the ascii value e.g. if ((str[i] >='a') && (str[i] <= 'z')) foundSym=0; and then repeat for uppercase. Or if you want to get fancy char tmp = str[i] | 0x20; if ((tmp >='a') && (tmp <= 'z')) foundSym=0; would check both upper and lower case.
    – Andrew
    Sep 29 '16 at 13:18
2

You are passing a pointer (char str[]) and the sizeof operator is giving you the size of that pointer (4 bytes it appears in your case - on some Arduinos it would be 2 bytes).

The length of a character array is found by using strlen - assuming the string is terminated by a null (0x00).

0
0

I think this will do the same as your code. I understand it doesn't directly answer the question, but I hope it shows you an alternative way of doing it using the library functions. But they are very difficult to find unless you know about them already.

void markSymbols(char* str)
{
  for(int i = 0; i < strlen(str); i++)
  {
    if (! ((isAlpha(str[i]) || (str[i] == ' ')))
    {  // If the character is not an letter of the alphabet (upper and lower case) and it is not a space (char 32).
        str[i] = '1';
     }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.