3

如果我要为一个 4 字节的变量初始化内存,我可以将两个 2 字节的变量指向为它存储的内存吗?我正在尝试进一步了解内存管理和理论。

我正在考虑的一个例子:

int main() {
    short* foo = malloc(4*(foo));    // sizeof(*foo)?
    /*in which sizeof will return 2 so I could say
      * malloc(20)
      * so could I say malloc(2*sizeof(long))?
      */
}

或者类型通常在堆上声明为彼此相邻,即一个块保留为长,而一个块保留为短类型变量?

编辑 我忘了包括一个问题。如果我要声明两个彼此相邻的 short 类型的变量(一个数组),我可以安全地将 long 指向第一项,并通过位图访问这两个变量吗?显然,这主要是针对理论的,因为我觉得对问题会有更好、更明显的答案。

4

4 回答 4

2

是的。当您分配内存时,C 并不关心类型 - 它只是一块与您请求的内存一样大的内存。它会让你在里面写,在它上面,在它下面……直到坏事发生!

如果您想要相邻值,则数组是一个不错的方法:

int *myAllocatedArray = (int*)calloc(2, sizeof(int));

myAllocatedArray[0] = 100;
myAllocatedArray[1] = 200;

calloc将每个字节初始化为 0。

于 2013-11-06T12:06:57.673 回答
1

当然,您可以根据需要访问它。从手册到 calloc() 和 malloc() 的信息很少:

SYNOPSIS
       #include <stdlib.h>

       void *malloc(size_t size);
       void *calloc(size_t nmemb, size_t size);
       ...

DESCRIPTION
       The  malloc() function allocates size bytes and returns a pointer to 
       the allocated memory.  The memory is not initialized.  If size is 0, 
       then malloc() returns either NULL, or a unique pointer value
       that can later be successfully passed to free().
       ...
       The  calloc() function allocates memory for an array of nmemb elements 
       of size bytes each and returns a pointer to the allocated memory.  The 
       memory is set to zero.  If nmemb or size is 0, then calloc() returns 
       either NULL, or a unique pointer value that can later be successfully 
       passed to free().
       ...
于 2013-11-06T12:08:11.567 回答
1

是的,它会起作用,因为 malloc 采用整数参数,例如: malloc(2*4)、4=sizeof(long) 或类似 malloc(20);

于 2013-11-06T12:08:23.440 回答
-1

是的,正如其他人所说,C 是一种弱类型语言。这意味着它几乎没有或没有类型转换的限制。

例如:

void *ptr;
unsigned int *m;
unsigned int *e;
double *d;

ptr = malloc(sizeof(double));

d = ptr;

m = ptr;
e = ptr + 6;

*d = 123.456f;

printf("mantissa: %u\nexponent: %u\ndouble: %f\n", *m, *e, *d);

/* Output:
 * mantissa: 536870912
 * exponent: 16478
 * double: 123.456001
 */
于 2013-11-06T12:38:53.737 回答