-1

非常に短い質問をさせてください:

文字の配列(小文字のみとしましょう)があり、各文字をアルファベットの次の文字にしたいです。「z」が「a」になると考えてください。私は使うだろう:

while (s[i] != '\0')
{
    if (s[i] == 'z')
        s[i] = 'a');
    else
        s[i] += 1;
    i++;
}

右?さて、ポインターを使用する必要がある場合は、代わりに次のように言います。

while (*s != '\0')
{
    if (*s == 'z')
        *s = 'a');
    else
        *s += 1; //Don't know if this is correct...
    s++; //edited, I forgot D:
}

ありがとうございました!

4

3 に答える 3

1

*s += 1正しい。i++に変更する必要もありますs++

于 2013-06-26T14:20:49.153 に答える
1

これは正しいでしょう:

while (*s != '\0')
{
    if (*s == 'z')
        *s = 'a');
    else
        *s += 1; //Don't think if this is correct... yes, it is
    s++; //small correction here
}
于 2013-06-26T14:20:55.997 に答える
0

sポインタとしてインクリメントする必要があります

while (*s != '\0')
{
    if (*s == 'z')
        *s = 'a';
    else
        *s += 1; //Don't think if this is correct...
    s++;
}

第二に、指している配列があるか、動的に割り当てられたメモリ(malloced string )があるかどうかについてです。これは、次のような文字列を変更できないためです。

char *str = "Hello, World!"; // is in read-only part of memory, cannot be altered

一方

char strarr[] = "Hello, World!"; //is allocated on stack, can be altered using a pointer
char* pstr = strarr;
*pstr = 'B'; //can be altered using a pointer -> "Bello, World!"

また

char* dynstr = malloc(32 * sizeof(char));
memset(dynstr, 0, 32);
strncpy(dynstr, "Hello, World!", 14); // remember trailing '\0'
char* pstr = dynstr;
*pstr = 'B'; // -> "Bello, World!"
于 2013-06-26T14:22:30.473 に答える