-8
int main() {
    //  int arr[2][2] = { {1,2}, {3,4}};
    int a[] = {1,2};
    int b[] = {3,4};
    int (*ptr)[2];

    // assign ptr to arr
    //ptr = arr;
    ptr = (int (*)[2])malloc (2*sizeof(int));
    ptr = &a;
    (ptr+1) = b;  // error here
     printf("%3d %3d", ptr[0][1], ptr[1][1]) ;
 }

我想要 (ptr+1) 分配一个数组,请帮帮我。谢谢。

4

4 回答 4

2

ptr是一个指向 int array( int[2]) 的指针,但是你 malloc 错误的大小,然后通过分配给相同的变量来泄漏内存,从而覆盖malloc内存地址。我假设你想这样做:

int (**ptr)[2];
ptr = malloc (2*sizeof(int(*)[2]));
ptr[0] = &a;
ptr[1] = &b;
于 2012-05-08T03:29:19.513 回答
0

Full code:

#include <stdlib.h>
#include <stdio.h>

int main() {
    int a[] = {1,2};
    int b[] = {3,4};
    int **ptr;

    ptr = (int **) malloc(sizeof(int *) * 2);

    ptr[0] = a;
    ptr[1] = b;
    printf("%3d %3d\n", ptr[0][1], ptr[1][1]);
    free(ptr);
 }

a and b already are pointers (to integers), so ptr is a pointer to a pointer (**).

于 2012-05-08T03:38:17.440 回答
0

You need to use an array of pointers, not a pointer to an array:

int main()
{
    int a[] = {1,2};
    int b[] = {3,4};
    int *ptr[2] = { a, b };

    printf("%3d %3d", ptr[0][1], ptr[1][1]) ;

    return 0;
}
于 2012-05-08T03:38:38.073 回答
0

你可以像这样 malloc 。

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    int i;
    int a[] = {1,2};
    int b[] = {3,4};
    int *ptr[2];    //same as ptr[2][??]

    ptr[0] = (int *) malloc(sizeof(int*) * 2);  //malloc ptr[0] >> 2 * sizeof int
    ptr[1] = (int *) malloc(sizeof(int*) * 5);  //malloc ptr[1] >> 5 * sizeof int

    /* so we get ptr[0][2] and ptr[1][5]*/

    /* SET VALUE */
    for(i = 0; i < 2; i++)
    ptr[0][i] = i;
    for(i = 0; i < 5; i++)
    ptr[1][i] = i;


    /* PRINT VALUE */
    for(i = 0; i < 2; i++)
        printf("ptr[0][%03d] = %03d\n", i, ptr[0][i]);

    printf("\n");

    for(i = 0; i < 5; i++)
        printf("ptr[1][%03d] = %03d\n", i, ptr[1][i]);


    /* FREE POINTER */
    free(ptr[0]);
    free(ptr[1]);

    return 0;
}
于 2012-05-08T04:23:43.620 回答