Search code examples
cmemory-address

Query on Address allocation in C


Can u pls help me undertand this basic item:

i have two varibale i and J , my query is i have initialized "I" and later on "J", but first address was allocated to J instead of "I".

Can u help me understand why ?

address for I and 4 bits higher than J

#include<stdio.h>
int main()
{
    int i;
    printf("%d",sizeof(int));
    printf("enter the number to multiply wuth 1 through 10:");
    scanf("%d",&i);
    printf("size of I:%d\n",sizeof(i));
    for(int j=0;j<=10;j++){
    
        printf("%d\n",i*j);
        printf("Address of j:%d\n",&j);
    }
    printf("%d",&i);
    return 0;
}


Solution

  • Compilers use their own algorithms to decide how to allocate memory among variables, based on many factors such as alignment and cache line usage. There is no guarantee that they will be arranged in memory in the same order as their declaration, nor any particular reason to expect this to be the case. (And unless you take the address of the variable, it may be optimized into a register which doesn't occupy memory at all.)