[-Win兼容指针类型]。不知道问题是什么

Abh*_*osh 2 c pointers incompatibletypeerror

我无法找到哪里出了问题。当我运行该程序时,它显示“访问被拒绝”。

#include<stdio.h>
int main()
{
    char arr[4][40] =
    { "array of c string",
        "is fun to use",
        "make sure to properly",
        "tell the array size"
    };
char *p = arr;  /*Char-4-eg-Find-the-output.c:10:11: warning: initialization of 'char *' from 
incompatible pointer type 'char (*)[40]' [-Wincompatible-pointer-types]*/
    for (int i = 0; i < 100; i++)
    {
        printf("%c",*p );
        p++;
   }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 5

表达式中使用的数组指示符(极少数例外)将转换为指向其第一个元素的指针。

所以在这个声明中

char *p = arr;
Run Code Online (Sandbox Code Playgroud)

数组指示符arr转换为指向其第一个元素的指针。数组元素的arr类型为char[40]。因此,指向该类型对象的指针的类型为char( * )[40]

然而,初始化的指针具有类型char *。并且不存在从 typechar ( * )[40]到 type 的隐式转换char *。所以编译器会发出一条消息。

要么你需要使用像

char *p = ( char * )arr;
Run Code Online (Sandbox Code Playgroud)

或写

char *p = arr[0];
Run Code Online (Sandbox Code Playgroud)

或者

char *p = &arr[0][0];
Run Code Online (Sandbox Code Playgroud)

如果你想将字符串数组作为一个句子输出,你可以这样写

#include <stdio.h>

int main(void) 
{
    enum { N = 40 };
    
    char arr[][N] =
    { 
        "array of c string",
        "is fun to use",
        "make sure to properly",
        "tell the array size"
    };
    

    for ( char ( *p )[N] = arr; p != arr + sizeof( arr ) / sizeof( *arr ); ++p )
    {
        if ( p != arr ) putchar( ' ' );
        printf( "%s", *p );
    }
    
    putchar( '\n' );
    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

程序输出是

array of c string is fun to use make sure to properly tell the array size
Run Code Online (Sandbox Code Playgroud)