类比数组和指针

时间:2013-06-26 14:19:05

标签: c pointers

让我问一个很短的问题:

我有一个字符数组(让我们说只有小写),我希望每个字符成为字母表的下一个字符。考虑'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:
}

谢谢!

3 个答案:

答案 0 :(得分:1)

*s += 1是正确的。您还需要将i++更改为s++

答案 1 :(得分: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
}

答案 2 :(得分:0)

您需要将s增加为指针

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

其次,它是关于,你是否有一个你指向的数组,或动态分配的内存(malloc ed 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!"