Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

F: malloc #71

Open
Konstantin8105 opened this issue Apr 21, 2018 · 1 comment
Open

F: malloc #71

Konstantin8105 opened this issue Apr 21, 2018 · 1 comment

Comments

@Konstantin8105
Copy link
Owner

test

struct MyNums {
    char name[100];
    int size;
    int numbers[];
};
void test_array_struct()
{
    int n = 10, k;
    struct MyNums *pnt;
    pnt = malloc(sizeof(struct MyNums) + n * sizeof(int));
    strcpy(pnt->name, "Натуральные числа");
    pnt->size = n;
    for (k = 0; k < pnt->size; k++)
        pnt->numbers[k] = k + 1;
	is_eq(pnt->numbers[2],3);
	is_eq(pnt->numbers[5],6);
}
@Konstantin8105
Copy link
Owner Author

void test_pointer_malloc1() {
    int m = 3, n = 5;
    int *p;
    p = malloc(m * n * sizeof(int));
    int i, j, count = 0;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            count++;
            p[i+j*m] = count;
        }
    }
	is_eq(p[0], 1);
	is_eq(p[2+2*m], 13);
    free(p);
}

void test_pointer_malloc2() {
    int m = 3, n = 5;
    int (*p)[n];
    p = malloc(m * n * sizeof(int));
    int i, j, count = 0;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            count++;
            p[i][j] = count;
        }
    }
	is_eq(p[0][0], 1);
	is_eq(p[2][2], 13);
    free(p);
}

void test_pointer_malloc3() {
    int m = 3;
    int (*p)[5];
    p = malloc(m * 5 * sizeof(int));
    int i, j, count = 0;
    for (i = 0; i < m; i++) {
        for (j = 0; j < 5; j++) {
            count++;
            p[i][j] = count;
        }
    }
	is_eq(p[0][0], 1);
	is_eq(p[2][2], 13);
    free(p);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant