Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- void testOne(int m[][2], int tam) {
- int x;
- for (x = 0; x < tam; x++) {
- m[x][0] = x;
- m[x][1] = x + 1;
- }
- }
- int* testTwo(int tam) {
- int* m;
- int x;
- m = malloc(sizeof(int) * 2 * tam);
- if (m == NULL) {
- printf("Error allocating memory!");
- exit(1);
- }
- for (x = 0; x < tam*2; x+=2) {
- m[x + 0] = x + 1;
- m[x + 1] = x + 2;
- }
- return m;
- }
- //this method is mased in something I found one Internet
- //you need to go deeper, and you are doing the same as above
- //http://stackoverflow.com/questions/8740195/how-do-we-allocate-a-2-d-array-using-one-malloc-statement
- //the method above is what I learned at university
- //I think, it's useful if you want an array (with unknown size) of pointers
- int** testThree(int tam) {
- int** m, x;
- m = (int**)malloc(tam * sizeof *m + (tam * (2 * sizeof **m)));
- if (m == NULL) {
- printf("Error allocating memory!");
- exit(1);
- }
- for (x = 0; x < tam*2; x+=2) {
- m[x + 0] = (int*)1;
- m[x + 1] = (int*)2;
- }
- return m;
- }
- int main() {
- int a[2][2], x, d = 2;
- int* b = NULL;
- int** c = NULL;
- testOne(a, d);
- for (x = 0; x < d; x++) {
- printf("%d, %d\n", a[x][0], a[x][1]);
- }
- b = testTwo(d);
- for (x = 0; x < d*2; x+=2) {
- printf("%d, %d\n", b[x + 0], b[x + 1]);
- }
- free(b);
- c = testThree(d);
- for (x = 0; x < d*2; x+=2) {
- printf("%d, %d\n", (int)c[x + 0], (int)c[x + 1]);
- }
- free(c);
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement