ground beef
ground beef

Reputation: 21

Casting pointer syntax (to an array address like a smaller sized array) in C language

I have an array with 10 int elements, and I want to point a pointer to this array, not with full size but half. By this, I can reach the first 5 elements by using ptr and the second 5 elements by increasing pointer one ptr++.

I just want to know how can I CAST, I don't need to know workarounds or union or struct or anything else... I just wonder the syntax of such a thing.

Here is the example that I struggle with ;

// Pointer to an integer 
int *p;
// Pointer to an array of 5 integers 
int (*ptr)[5]; // this could be void*
int arr[10]; 

// Points to 0th element of the arr. 
p = arr; 

// Points to the whole array arr. 
ptr = (int[5]*)&arr; // when arr sized as 5 , ptr = &arr; gives result a pointer "ptr" with size of 5  

printf("p = %p, ptr = %p\n", p, ptr); 

p++; 
ptr++; 

printf("p = %p, ptr = %p\n", p, ptr); 

return 0; 

Note: The answer is: ptr = (int(*)[5])&arr; (compiler's warning message helped me out to find this answer, it was not able to convert one to another type ... )

But I really don't know what is the () and why it is not the same thing as int*[5]. I really don't understand the purpose of parenthesis there.

Upvotes: 2

Views: 576

Answers (2)

John Bode
John Bode

Reputation: 123488

If I understand what you’re asking for, this is what you want:

ptr = (int (*)[5]) &arr;

The expression &arr has type int (*)[10] (pointer to 10-element array of int). Since ptr has type int (*)[5] (pointer to 5-element array of int), we just need to cast the result of &arr to that type.

Remember the following precedence rules:

T *a[N];        // a is an array of pointer to T
T (*a)[N];      // a is a pointer to an array of T
T *f();         // f is a function returning pointer to T
T (*f)();       // f is a pointer to a function returning T

Unary * has a lower precedence than [] and (), so an expression like *a[i] is parsed as *(a[i]) - you’re dereferencing the result of a[i]. If a is a pointer to an array, then you need explicitly group * with a so you index into what a points to - (*a)[i].

Upvotes: 1

Barmar
Barmar

Reputation: 781300

Define a typedef to make the casting easier.

typedef int (*int5ptr)[5];

// Pointer to an integer 
int *p;
// Pointer to an array of 5 integers 
int5ptr ptr;
int arr[10]; 

// Points to 0th element of the arr. 
p = arr; 

// Points to the whole array arr. 
ptr = (int5ptr)&arr;

printf("p = %p, ptr = %p\n", p, ptr); 

p++; 
ptr++; 

printf("p = %p, ptr = %p\n", p, ptr); 

Upvotes: 0

Related Questions