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. 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.
CodePudding user response:
The type of &buffer
is unsigned char (*)[size]
.
The type of ptr
is 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. And that's what plain buffer
will decay to:
ptr = buffer;
CodePudding user response:
I made a minor change to the code you provided, 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;
}