无聊,测试P[][4]的内存分配

tt posted @ 2008年3月21日 00:44 in C语言编程 , 2180 阅读

在程序的函数中,有可能碰到类似 float p[][4] 的参数,我们可以用下面的方式为其定义并分配内存,见下面的程序代码:

#include<stdio.h>
#include<malloc.h>

int main()
{
    int (*p)[4];

    int  n=10;

    p=malloc(n*4*sizeof(int));
    int i=0;
    for (i=0; i<10; i++)
    {
    p[i][0]=i;
    p[i][1]=i;
    p[i][2]=i;
    p[i][3]=i;
    }
    for(i=0; i<10; i++)
    {
    printf("%d %d %d %d\n", p[i][0], p[i][1], p[i][2], p[i][3]);
    }
    printf("%d\n",sizeof(p));
    return 0;
}

不知道这种内存分配方式是否规范,将其视为单指针进行内存分配。

也可以采用以下方法定义和分配内存:

    int **p=malloc(n*sizeof(int*));

    for (int i=0; i<n; i++)

    {

       p[i]=malloc(4*sizeof(int));

    }

Avatar_small
celeb networth 说:
2022年9月23日 17:40

It's a good chance to know more about these stories, very interesting and meaningful. And please take a look at this site, where I find the all the information I need about celeb networth post


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter