gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:21:58 25 4
gpt4 key购买 nike

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

#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;
}

最佳答案

在极少数情况下,表达式中使用的数组指示符会转换为指向其第一个元素的指针。

所以在这个声明中

char *p = arr;

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

然而,初始化指针的类型为 char *。并且没有从类型 char ( * )[40] 到类型 char * 的隐式转换。因此编译器发出一条消息。

要么你需要像这样使用转换

char *p = ( char * )arr;

或写

char *p = arr[0];

char *p = &arr[0][0];

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

#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;
}

程序输出为

array of c string is fun to use make sure to properly tell the array size

关于c - [-Win 兼容指针类型]。不知道是什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67988125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com