1

I'm still a little new to C, and one hiccup I've been stuck on for the past bit is iterating through a char array received as a parameter. The char array was created as a String literal and passed as an argument. From my understanding this array being received as simply a pointer to the first element in the array; my goal is to loop through each element until reaching the end of the String literal that was passed.

Since I'm required to perform comparisons of each char to char literals inside the loop, I've assigned the value being pointed at in the array, to a char variable that is being used for the comparisons.

Where I'm having trouble is specifying at what point this loop should end.

int main (int argc, char* argv[])
{
    testString("the quick brown fox jumped over the lazy dog");

    return EXIT_SUCCESS;
}

void testString(char line[])
{
    int i = 0;
    int j = 0;
    char ch;
    ch = line[i];

    char charArray[128];

    while (ch != '\0')    // Not sure why this doesn't work
    {   

        if ((ch == '\'' || ch == '-'))
        {
            charArray[j] = ch;
            j++;
        }
        else if (isalpha(ch))
        {
            charArray[j] = ch;
            j++;
        }
        else
        {
             // do nothing
        }

        i++;
        ch = line[i];
    }
}

Thanks in advance for any advice you can offer.

6
  • and learn how to use a debugger Commented Feb 2, 2016 at 21:58
  • The program will terminate when the loop finds the end mark of the string. The end of string is represented by '\0'. Commented Feb 2, 2016 at 22:01
  • 2
    What do you mean by it doesn't work? It looks like the loop terminates fine - you just don't do anything with the resulting charArray. (note that if/when you do something with charArray you'll probably need to make sure it's properly terminated with a null character which isn't happening now). Commented Feb 2, 2016 at 22:01
  • 3
    @pm100 it's already inside the loop, although badly indented. Commented Feb 2, 2016 at 22:01
  • 1
    It might be wise to check that j does not exceed the bounds of charArray - i.e. 127. Commented Feb 2, 2016 at 23:18

1 Answer 1

3

The exit condition for your loop is working fine.

The only thing missing is that you need to null terminate charArray after the while loop and print it out:

while (ch != '\0')
{
    ...
}
charArray[j] = '\0';
printf("charArray=%s\n",charArray);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.