Hi, I'm trying to figure out dynamic memory allocation in C, but I'm pretty sure my code is incorrect. I'm trying to set aside a contiguous block of memory of size in bytes of the users choosing, but the addresses I'm getting back are not sequential. Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int bytes = 0;
int *pointer;
printf("Please enter the amount of bytes you wish to set aside: ");
scanf("%d", &bytes);
pointer = malloc(bytes);
if(pointer == NULL)
{
printf("Memory could not be allocated.");
}
else
{
printf("You have set aside %d bytes.\n", bytes);
printf("The addresses of the memory are:\n");
for(int i = 0; i < bytes; i++)
{
printf("%p\n", *(pointer + i));
}
}
free(pointer);
return 0;
}
Okay, using char makes it look like a contiguous block of memory. Why is it though that when setting aside memory for an integer pointer, the addresses jump by four places each time? I thought that no matter what data type you used, the block of memory had to be contiguous. I understand that an integer will use four bytes of memory, but is that four bytes not stored at one memory address location?
So am I right in thinking that one byte is equal to one memory address and likewise, four bytes is equal to four memory addresses, each in a contiguous block?