Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to first element in array! (C)

Tags:

arrays

c

pointers

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

like image 779
Phil Avatar asked Jul 10 '11 04:07

Phil


2 Answers

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
like image 114
Dietrich Epp Avatar answered Oct 22 '22 02:10

Dietrich Epp


& 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].

like image 42
catfish_deluxe_call_me_cd Avatar answered Oct 22 '22 00:10

catfish_deluxe_call_me_cd