Skip to content

Instantly share code, notes, and snippets.

@Maksim-Zhuravlev
Created October 4, 2017 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Maksim-Zhuravlev/a7e8606379835edbaf38f6c60ed1663e to your computer and use it in GitHub Desktop.
Save Maksim-Zhuravlev/a7e8606379835edbaf38f6c60ed1663e to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
void main() {
int **data = NULL;
size_t rows = 4, columns = 5;
size_t alloc_size = rows * sizeof(int*) + rows * columns * sizeof(int);
data = (int **)malloc(alloc_size);
if (!data) {
perror("Cannot allocate memory");
exit(1);
}
printf("data = %p\n", data);
for (int i = 0; i < rows; i++) {
data[i] = (int*)((char *)data + sizeof(int *) * rows + i * columns * sizeof(int));
printf("&data[%d] = %p\n", i, &data[i]);
printf("data[%d] = %p\n", i, data[i]);
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
data[i][j] = 'A' + i * columns + j;
}
}
char * data2 = (char *) data;
char * end = data2 + alloc_size;
while(data2 < end) {
printf("%c ", *data2);
data2++;
}
free(data);
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment