简体   繁体   中英

Pointer to first element in array! (C)

I'm new to C.

I know this has been asked in many forms but mine is a little unique...I guess. I have an unsigned short pointer.

6 unsigned short *pt;  
7 pt = myArray[0];

The array is declared as such: const unsigned short myArray[1024] and is an array of hex numbers of the form 0x0000 and so on.

I try to compile, it throws these errors:

myLib.c:7: error: data definition has no type or storage class
myLib.c:7: error: type defaults to 'int' in declaration of 'pt'
myLib.c:7: error: conflicting types for 'pt'
myLib.c:6: note: previous declaration of 'pt' was here
myLib.c:7: error: initialization makes integer from pointer without a cast

any ideas of what's going wrong?

Thanks, Phil

My guess (you only show two lines) is that this code appears outside a function. This is a statement:

pt = myArray[0];

Statements must go in functions. Also, if myArray has type unsigned short[] , then you want to do one of these instead:

pt = myArray;
pt = &myArray[0]; // same thing

& is the reference operator. It returns the memory address of the variable it precedes. Pointers store memory addresses . If you want to "store something in a pointer" you dereference it with the * operator. When you do that the computer will look into the memory address your pointer contains, which is suitable for storing your value.

char *pc; // pointer to a type char, in this context * means pointer declaration
char letter = 'a'; // a variable and its value

pc = &letter; // get address of letter
// you MUST be sure your pointer "pc" is valid

*pc = 'B'; // change the value at address contained in "pc"

printf("%c\n", letter); // surprise, "letter" is no longer 'a' but 'B'

When you use myArray[0] you don't get an address but a value, that's why people used &myArray[0] .

Yeah, you really should include a bit more code so we can see the context.

I don't quite get the error messages, but your code is not correct.

Try:

pt = &myArray[0];

Or:

pt = myArray + 0;

Or just:

pt = myArray;

Instead.

You should not throw away the const qualifier; so the pointer should have a const modifier.

const unsigned short myArray[1024];
const unsigned short * pointer = myArray;  // set pointer to first element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM