That's actually correct behaviour. There is a subtle difference between array names and pointers that is easy to forget.
In C, the array name is an alias for the address where the array is located, but a pointer has storage allocated that holds a memory address.
So:
extern int ptr[];
a = ptr[1];
should translate to:
ld hl,(_ptr + 1*sizeof(int))
notice how "_ptr" is taken as the address of the array in memory.
But this:
extern int *ptr;
a = ptr[1];
should translate to:
ld hl,(_ptr)
inc hl
inc hl ;; move to second element in array
ld e,(hl)
inc hl
ld d,(hl)
Notice that "_ptr" holds the address of the pointer's value which must be loaded first and then indexed from.
I tried a few compiles with your source code:
Code: Select all
#include <stdio.h>
extern int *ptr;
void main() {
printf("%d, %d", ptr[0], ptr[1]);
}
zcc +zx -vn -a -clib=new test.c
Code: Select all
ld hl,(_ptr)
ld e,(hl)
inc hl
ld d,(hl)
push de
ld hl,(_ptr)
inc hl
inc hl
call l_gint ;
zcc +zx -vn -a -SO3 -clib=sdcc_iy test.c
Code: Select all
ld hl,(_ptr)
inc hl
inc hl
ld c,(hl)
inc hl
ld b,(hl)
ld hl,(_ptr)
ld e,(hl)
inc hl
ld d,(hl)
Both compilers are correctly reading the ptr value and then indexing off that.
With this:
Code: Select all
#include <stdio.h>
extern int ptr[];
void main() {
printf("%d, %d", ptr[0], ptr[1]);
}
zcc +zx -vn -a -clib=new test.c
Code: Select all
ld hl,(_ptr)
push hl
ld hl,(_ptr+1+1)
push hl
zcc +zx -vn -a -SO3 -clib=sdcc_iy test.c
Both compilers are using "_ptr" as the start address of the array.
For:
The correct asm for generating that array is:
Code: Select all
SECTION rodata_user
PUBLIC _ptr
_ptr: defw 0, 1, 2, 3 // array contents
For:
The correct asm for generating an array that is initially pointed at by "ptr" is:
Code: Select all
SECTION data_user
PUBLIC _ptr
_ptr: defw my_array
SECTION rodata_user
my_array: defw 0, 1, 2, 3 // array contents
Notice I'm also making a distinction here between rodata_user and data_user; the former holds constant non-zero values that can be placed in ROM while the latter holds non-zero values that are held in RAM and can be changed.
The "const int ptr[]" is an array of constant integers which means the array contents can be defined in ROM (ie rodata_user).