如何在C中访问分配的内存?

时间:2011-11-13 04:09:26

标签: c data-structures

使用malloc()初始化5000字节的内存后,如何引用此内存空间中的字节?例如,如果我需要指向内存中数据的起始位置,我该怎么做呢?

编辑:我用它来指出它是否重要?我的意思是我看到人们使用bytes / int / char?它有用吗?

我得到的错误: enter image description here

6 个答案:

答案 0 :(得分:1)

char * buffer = malloc(5000);

buffer[idx] = whatever;

char * p = buffer + idx;
*p = whatever;

答案 1 :(得分:1)

您可以使用下标array[n]运算符来访问您感兴趣的读/写索引,如下所示:

uint8_t* const bytes = (uint8_t*)malloc(5000);

bytes[0] = UINT8_MAX; // << write UINT8_MAX to the first element
uint8_t valueAtIndexZero = bytes[0]; // << read the first element (will be UINT8_MAX)
...
free(bytes), bytes = 0;

答案 2 :(得分:0)

Malloc不会初始化它分配的位。请使用calloc()

int *p = malloc (5000); // p points to the start of the dynamically allocated area.

答案 3 :(得分:0)

malloc()返回指向已分配内存的指针:

typedef unsigned char byte;
byte * mem = malloc( 5000 );

byte val = mem[1000]; /* gets the 1000th byte */

答案 4 :(得分:0)

正如其他人所提到的,你可以这样做:

int nbytes = 23; // number of bytes of space to allocate
byte *stuff = malloc(nbytes * sizeof stuff[0]);

stuff[0] = 0; // set the first byte to 0
byte x = stuff[0]; // get the first byte

int n = 3;
stuff[n] = 0; // set the nth byte to 0
x = stuff[n]; // nth byte, or in the case of some other type, nth whatever - just make sure it's a safe value, from 0 (inclusive) to the number (nbytes here) of things you allocated (exclusive)

然而,有几点需要注意:

  1. malloc不会初始化内存,但calloc会(如Prasoon Saurav所述)
  2. 您应该始终检查内存分配是否失败(请参阅下面的示例)
  3. int nbytes = 23; // or however many you want  
    byte *stuff = malloc(nbytes * sizeof stuff[0]);
    
    if (NULL == stuff) // memory allocation failed!
    {
     //handle it here, e.g. by exiting the program and displaying an appropriate error message
    }
    
    stuff[0] = 0; // set the first byte to 0
    byte x = stuff[0]; // get the first byte
    
    int n = 3;
    stuff[n] = 0; // set the nth byte to 0
    x = stuff[n]; // nth byte, or in the case of some other type, nth whatever
    

答案 5 :(得分:0)

  

使用malloc()初始化5000字节的内存后,我该怎么做   引用此内存空间中的字节?例如,如果我需要   指向内存中数据的起始位置,我该怎么做   关于那个?

     

我用它来指出它是否重要?我的意思是我在看人   使用bytes / int / char?它有用吗?

正如您所看到的,malloc分配以字节为单位的内存块,您可以根据指针类型分配指向该块的指针和 ,编译器知道如何引用单个元素:

unsigned char *memblob = malloc( 1024 );
short* pshort = (short*)memblob; 

现在如果引用第二个短值,即*(pshort + 1)pshort[1],编译器就知道它需要添加2个字节(sizeof(short))才能获得下一个元素。

float* pfloat = (float*)memblob;

现在如果引用第二个浮点值,即*(pfloat + 1)pfloat[1],编译器就知道它需要添加4个字节(sizeof(float))才能获得下一个元素。

与自己定义的数据类型相同:

typedef struct s
{
  short a;
  long  b;
} mystruct_t;

mystruct_t* pstruct = (mystruct_t*)memblob; 

pstruct + 1访问偏移struct

sizeof(mystruct_t)

所以你真的要按照你想要的方式使用分配的内存

相关问题