简体   繁体   中英

What is the difference between this loop using array bracket vs pointer notation in C?

In the C programming language, I have the following code:

void rm_newline(char input[])
{
    assert(input);
    size_t i;
    for(i = 0; input[i] != '\0'; ++i)
    {
        if(input[i] == '\n') input[i] = '\0';
    }
    return;
}

This code works as intended by replacing a '\\n' char with '\\0'. However I had a previous version shown below:

void rm_newline(char input[])
{
    assert(input);
    char *input_ptr = input;
    while(*input_ptr != '\0')
    {
        if(*input_ptr++ == '\n')
        {
            *input_ptr = '\0';
        }
    }
    return;
}

This second code was not properly replacing the '\\n' with '\\0' but I'm not sure why. Would someone please explain how the second code is functionally different from the first code?

In the second case,

 if(*input_ptr++ == '\n')

input_ptr is incremented before the body of the conditional executes. You need to increment after the replacement is done, something like

while(*input_ptr != '\0')
{
    if(*input_ptr == '\n')
    {
        *input_ptr = '\0';  
    }
     input_ptr++; // do the increment here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM