Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#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