如果我尝试创建一个全局数组来保存任意数量的整数,在本例中为 2 个整数。如果我只为两个整数分配足够的空间,我怎么可能给它分配更多的数字。
int *globalarray;
int main(int argc, char *argv[]) {
int size = 2;
globalarray = malloc(size * sizeof(globalarray[0]));
// How is it possible to initialize this array pass
// the two location that I allocated.
for (size_t i = 0; i < 10; i++) {
globalarray[i] = i;
}
for (size_t i = 0; i < 10; i++) {
printf("%d ", globalarray[i]);
}
printf("%s\n", "");
int arrayLength = sizeof(*globalarray)/sizeof(globalarray[0]);
printf("Array Length: %d\n", arrayLength);
}
当我运行它时,它会给我
0 1 2 3 4 5 6 7 8 9
Array Length: 1
所以我想知道是否有人可以帮我澄清这一点。
(1) 我是否正确创建了全局数组?
(2)为什么数组长度为1?当我觉得它应该是 2 时,因为我将指针 malloc 为 2。
关于我为什么想知道这一点的背景信息是因为我想创建一个全局数组(共享数组),以便线程稍后可以访问该数组并更改值。
最佳答案
How is it possible to initialize this array pass the two location that I allocated.
简短回答:这是未定义的行为,任何事情都可能发生,而且它起作用的外观也是如此。
长答案:你只能初始化你分配的内存,它 该变量是全局变量并不重要。 C 不会阻止你 越界,但如果你这样做,那么你会得到未定义的行为,任何事情都可能发生 (它可以“工作”,但也可能立即崩溃或稍后崩溃)。
因此,如果您知道需要 10 int
,则为 10 int
分配内存。
globalarray = malloc(10 * sizeof *globalarray);
if(globalarray == NULL)
{
// error handling
}
如果您以后需要更多,比如说 15,那么您可以使用 realloc
来增加
内存分配:
globalarray = malloc(10 * sizeof *globalarray);
if(globalarray == NULL)
{
// error handling
// do not contiue
}
....
// needs more space
int *tmp = realloc(globalarray, 15 * sizeof *globalarray);
if(tmp == NULL)
{
// error handling
// globalarray still points to the previously allocated
// memory
// do not continue
}
globalarray = tmp;
<小时/>
Am I creating the global array correctly?
是和否。它在语法上是正确的,但在语义上却不是,因为你是
仅为 2 int
分配空间,但从下一行可以清楚地看出
您需要 10 int
。
Why is the array length 1? When I feel that it should be 2 since I malloced the pointer for 2.
那是因为
sizeof(*globalarray)/sizeof(globalarray[0]);
仅适用于数组,不适用于指针。另请注意,您在以下情况中使用了错误的方法 两种方式:
- 正确的公式是
sizeof(globalarray)/sizeof(globalarray[0])
- 这只适用于数组,不适用于指针(见下文)
当我们做事情时,我们有时会使用术语“数组”作为视觉表示 就像
int *arr = malloc(size * sizeof *arr)
但是arr
(和globalarray
)不是数组,
它们是指针。 sizeof
返回大小的字节数
表达/变量需求。在您的情况下 *globalarray
的类型为 int
并且
globalarray[0]
也具有 int
类型。所以你正在做 sizeof(int)/sizeof(int)
显然是 1。
就像我说的,这只适用于数组,例如,这是正确的
// not that arr here is not an array
int arr[] = { 1, 2, 3, 4 };
size_t len = sizeof arr / sizeof arr[0]; // returns 4
但这是不正确的:
int *ptr = malloc(4 * sizeof *ptr);
size_t len = sizeof ptr / sizeof ptr[0]; // this is wrong
因为sizeof ptr
没有返回分配的总量
bytes,它返回指针需要在内存中存储的字节数。当你正在处理
指针,您必须有一个单独的变量来保存大小。
关于有人可以解释一下吗?它处理 C 中的 malloc 和全局数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49565232/