C:不兼容的指针类型初始化 [英] C: Incompatible pointer type initializing
问题描述
我想学C.我目前在指针所以我决定写一些code,看看它是如何工作的。然而,code按预期工作(即它增加了一个字符-J在一个数组并打印在控制台上),但我得到有关兼容的指针赋值警告。我已经添加了警告,因为上线评论被警告中给出。
I'm trying to learn C. I'm currently on pointers so I've decided to write some code to see how it works. However the code works as intended (i.e. it adds chars a-j in an array and prints it on the console) but I'm get warnings about incompatible pointer assignment. I've added the warnings as comments on the lines were the warnings are given.
#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;
}
有人可以解释为什么我得到这些警告?
Can someone please explain why I'm getting these warnings?
char* pointer = &c; & pointer = &c;
据我所知,code我写如下声明一个字符指针称为指针和数组指针在分配1个元素的地址。
I understand the code I'm writing as follows declare a char pointer called pointer and assign the address of the 1st element in the array to the pointer.
PS!请不要在如何实现更好的书面code相同的结果,我想在这里了解指针和数组发表评论。因此,尽管这可能是实现这一结果的详细办法,我觉得这是语法正确的,所以如果我有这错了,请帮助我理解。
PS! please don't comment on how to achieve the same result with better written code as I'm trying to learn here about pointers and arrays. So while this may be a verbose way to achieve this result, I feel it is syntactically correct, so if I've got this wrong please help me understand.
推荐答案
修改
char* pointer = &c
到
char* pointer = c[0];
C
元素类型是的char *
,但和C
类型是一个指向 C
键入
c
elements type is char *
but &c
type is a pointer to c
type.
修改:这将解决您的警告,但问题是你第一次处理错误的类型
EDIT: This will fix your warning but the problem is you are dealing with the wrong types first.
而不是:
char* c[MAX];
char* pointer = &c;
使用:
char c[MAX];
char *pointer = c;
在你的程序你存储的字符,所以你需要字符
的数组,而不是数组的char *
元素。
In your program you are storing characters, so you need an array of char
and not an array of char *
elements.
同为指针=和C;
,然后必须是指针= C;
这篇关于C:不兼容的指针类型初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!