230k views
4 votes
When a variable is stored in memory, it is associated with an address. To obtain the address of a variable, the & operator can be used. For example, &a gets the memory address of variable a. Let's try some examples.

Write a C program addressOfScalar.c by inserting the code below in the main function.

Questions:
1) Run the Cprogram, attach a screenshot of the output in the answer sheet.
2) Attach the source code in the answer sheet
3) Then explain why the address after intvar is incremented by 4 bytes instead of 1 byte.

User Thermatix
by
6.3k points

1 Answer

3 votes

Answer:

Step-by-step explanation:

1) C program file addressOfScalar.c

#include <stdio.h>

int main()

{

//intialize a char variable, print its address and the next address

char charvar = 'a';

printf("address of charvar = %p\\", (void *)(&charvar));

printf("address of charvar - 1 = %p\\", (void *)(&charvar - 1));

printf("address of charvar + 1 = %p\\", (void *)(&charvar + 1));

//intialize a int variable, print its address and the next address

int intvar = 1;

printf("address of intvar = %p\\", (void *)(&intvar));

printf("address of intvar - 1 = %p\\", (void *)(&intvar - 1));

printf("address of intvar + 1 = %p\\", (void *)(&intvar + 1));

}

In C programming language, an int variable takes 4 bytes of memory. So any arithmetic on integer address, always considers it as 4 bytes of data. So intvar-1 refers to a location 4 bytes before intvar's address and intvar+1 refers to 4 bytes after intvar's address.

User RamiroPastor
by
6.0k points