C 数组和指针的类比

C 数组和指针的类比,c,pointers,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')

让我问一个非常简短的问题:

我有一个字符数组(比如说只有小写),我希望每个字符都成为字母表的下一个。把“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:
}

谢谢大家!

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

这是正确的:

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
}

您需要将
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!"


s++,而不是i++中的循环代码审查,简单的错误由作者所犯;保持它打开没有意义。这个问题没有问题。动态分配的内存不是问题。问题案例指向字符串文字或使用
const
定义的对象。(请注意,指向使用字符串文字初始化的数组与指向字符串文字不同。)否则,对象是否具有静态、自动或分配的存储持续时间无关紧要。
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!"