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';
  }

}
paulj
  • 13
  • 2

2 Answers2

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).

Nick Gammon
  • 38,901
  • 13
  • 69
  • 125
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';
     }
  }
}
Code Gorilla
  • 5,652
  • 1
  • 17
  • 31