[英]Unsigned char pointer pointing to an unsigned char array
I'm trying to make an array of unsigned char's and make a pointer which points to the first position of the array but I keep getting an error.我正在尝试制作一个无符号字符数组,并制作一个指向数组第一个 position 的指针,但我一直收到错误消息。 This is my code as well as the error:
这是我的代码以及错误:
void initBuffer
{
unsigned char buffer[size];
unsigned char *ptr;
ptr = &buffer;
}
I suspect it's a very simple type error buy I'm new to C and not sure how to fix it.我怀疑这是一个非常简单的类型错误购买我是 C 的新手并且不确定如何修复它。
The type of &buffer
is unsigned char (*)[size]
. &buffer
的类型是unsigned char (*)[size]
。
The type of ptr
is unsigned char *
. ptr
的类型是unsigned char *
。
Those two types are not the same.这两种类型是不一样的。 Just as the compiler tells you.
就像编译器告诉你的那样。
Assuming you want to make ptr
point to the first elements of buffer
then you need to use &buffer[0]
which has the correct type.假设你想让
ptr
指向buffer
的第一个元素,那么你需要使用具有正确类型的&buffer[0]
。 And that's what plain buffer
will decay to:这就是普通
buffer
将衰减为:
ptr = buffer;
I made a minor change to the code you provided, ptr = &buffer[0];我对您提供的代码做了一个小改动,ptr = &buffer[0];
#include <stdio.h>
int main() {
unsigned char buffer[] = {'A','B','C','D'};
unsigned char *ptr;
ptr = &buffer[0]; // ptr, points to first element of array
for(int i=0; i<4; i++)
printf("%c", ptr[i]);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.