-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 字符串),因为您无法更改类似的字符串

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 回答