Forum: System Workbench for STM32

Pointer Artimetic Gets Compiler Warning

The code:

 
int testar[] = {1,2,3};
int * ptestar;
ptestar = &testar+1;

Gets on its last line the warning:

xxxxxxxxxx
 
assignment from incompatible pointer type

Why would this pointer arithmetic cause this error? What is the right way to do this?

&testar is of **int type. Try this:

int testar[] = {1,2,3};
int * ptestar;
ptestar = testar+1;

P.S.

You can expect quick answers with this type of questions (C language question unrelated to the IDE or STM32) in other general C programming forums.


xxxxxxxxxx
 
ptestar = testar+1;

is not equivalent to

xxxxxxxxxx
 
ptestar = &testar+1;

The former is the same as

xxxxxxxxxx
 
ptestar = &testar[1];

This is not what I am seeking to do, which is to get a pointer to a location just beyond the bounds of the array to find the array size by the method I describe in this thread:
http://www.openstm32.org/tiki-view_forum_thread.php?forumId=7&comments_parentId=1612Question

I have given up on that method. I realize now there is no advantage to doing it that way over the use of the sizeof operator.


France

Hi,

If you want to have the address after the testar array you must declare ptestar as a pointer to a pointer to int (as it is really the address of an array of 3 ints...):
xxxxxxxxxx
 
int **ptestar = &testar+1;
However, there is two things to note about your code:
  1. If you follow strictly the C standard, your C program is not standard compliant, as pointer arithmetic is restricted to stay inside a single C object, while you code use pointer arithmetic to point to a integer array located after the testar object
  2. If you want to be clearer that what follows testar is not another integer array, you may devlare ptestar as a pointer to void:
    xxxxxxxxxx
     
    void *ptestar = &testar+1;
  3. Obviously, the testar declaration must be an array definition that provides the compiler with the size of the array; it cannot be an external declaration of a variable size array as, in this case, the compiler will not have any way, at compile time, to know the size of the array: it will only be known at link time, too late for the compiler to use it.

Hope this helps,

Bernard (Ac6)