C: 不兼容的指针类型初始化

She*_*y75 5 c arrays pointers

我正在尝试学习 C。我目前正在使用指针,所以我决定编写一些代码来看看它是如何工作的。然而,代码按预期工作(即,它在数组中添加字符 aj 并将其打印在控制台上),但我收到有关不兼容的指针分配的警告。我已将警告添加为警告所在行的注释。

#include <stdio.h>
#include <stdlib.h>


int main(int argc, const char * argv[]) {

    #define MAX 10

    char* c[MAX]; // pointer to the 1st element in the array
    char* pointer = &c; // Warning: Incompatible pointer types initializing 'char *' with an expression of type 'char *(*)[10]'
    for (int j = 0; j < 10; j++)
    {
        *pointer = 'a' + j;
        pointer++;
    }

    pointer = &c; // Warning: Incompatible pointer types assigning to 'char *' from 'char *(*)[10]'
    for (int j = 0; j < 10; ++j)
    {
        printf("i[%d] = %c\n", j, *pointer);
        ++pointer;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下为什么我收到这些警告吗?

char* pointer = &c; & pointer = &c;
Run Code Online (Sandbox Code Playgroud)

我理解我正在编写的代码如下,声明一个称为指针的字符指针,并将数组中第一个元素的地址分配给该指针。

附言!请不要评论如何使用更好的编写代码来实现相同的结果,因为我正在尝试在这里学习指针和数组。因此,虽然这可能是实现此结果的一种冗长方式,但我认为它在语法上是正确的,所以如果我弄错了,请帮助我理解。

oua*_*uah 5

改变:

char* pointer = &c
Run Code Online (Sandbox Code Playgroud)

char* pointer = c[0];
Run Code Online (Sandbox Code Playgroud)

c元素类型是类型char *,但&c类型是指向类型的指针c

编辑:这将解决您的警告,但问题是您首先处理错误的类型。

代替:

char* c[MAX];
char* pointer = &c;
Run Code Online (Sandbox Code Playgroud)

使用:

char c[MAX];
char *pointer = c;
Run Code Online (Sandbox Code Playgroud)

在您的程序中,您要存储字符,因此您需要一个数组char而不是元素数组char *

相同的pointer = &c;then 必须是pointer = c;