Olcay E.
Olcay E.

Reputation: 41

Internal Array Element Location Algorithm

I'm trying to understand several concepts in C and one of these is the arrays. Well, in the book, there is an explanation about the internal array element location algorithm.

Each element in an array is reached by adding an offset to the starting address of the array

– Address element i = starting array address + offset

For single-dimensional arrays:

– Offset = i * the size of an individual element

However,

#include <stdio.h>
#define  NUMELS 20
int main() {
int numbers[NUMELS];

printf("The starting address of the numbers array is: %d\n", &(numbers[0]));
printf("The storage size of each array element is: %d\n", sizeof(int));
printf("The starting address of the numbers[5] array is: %d\n", &(numbers[5]));
return 0;
}

when this code executed on macos, the result is;

The starting address of the numbers array is: -346695536
The storage size of each array element is: 4
The starting address of the numbers[5] array is: -346695516

on the another hand, when this code executed on windows, the result is;

The starting address of the numbers array is: 16514000
The storage size of each array element is: 4
The starting address of the numbers[5] array is: 16514020

My question is about the locating the arrays on the memory. Why does windows use unsigned numbers, whereas mac uses signed numbers?

Edit: Btw, i have executed these codes on the same ide. (clion). I know i should be using %p format specifier, but in the book, it was using %d format specifier. So I was just wondering the reason of difference on the results. Thanks for replies!

Upvotes: 1

Views: 92

Answers (1)

dbush
dbush

Reputation: 224387

The internal memory layout of a program is specific to each implementation. Addresses of variables are rarely the same in programs generated by two different compilers. In fact, they can even differ on multiple runs of the same program.

Also, when printing pointers, you should be using the %p format specifier. You should also cast any pointer you print using %p to void * which is the expected type for this format specifier. That's part of the reason why you see negative values for the addresses. When you switch to %p, you'll most likely see non-negative values.

Upvotes: 2

Related Questions