我尝试使用指针和 malloc() 函数创建一个数组,然后通过 for 循环对其进行初始化,但并非所有值都已初始化并且有些似乎以不同的方式对待,我不明白。
在第一个版本中,我编写了没有强制转换的 for
循环,这导致在使用 -Wall 编译时出现
,并且在执行时给出了相同的结果。警告:有符号和无符号整数表达式之间的比较
- Wextra
#include <stdio.h>
#include <stdlib.h>
#define N 50
#define SIZE sizeof(int)
void afficher (int *p) /* just to display the values of the array*/
{
int i;
for (i=0; i<=(int) ((N-1)*SIZE); i+=SIZE)
{
printf("%d ", *(p+i));
}
printf("\n\n");
}
int main()
{
int * pointer = NULL;
int i;
pointer = malloc (N*SIZE);
afficher(pointer); /*first display before initialising*/
if (pointer)
{
for (i=0; i<=(int)((N-1)*SIZE); i+=SIZE)
{
*(pointer+i) = 1; /*trying to initialise all values to 1 */
}
}
afficher(pointer); /*second display*/
free(pointer);
return 0;
}
因此,虽然我希望第一个显示器能够显示程序启动之前内存中的内容,但我希望第二个显示器上的所有值均为 1,但我得到的是
0 0 0 0 0 0 0 0 0 0 0 0 0 540024880 540024880 540031032 825438256 8246 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1 1 540090417 540090417 540487988 926430256 8246 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
尽管第一个显示有点奇怪,但我认为当我尝试更改值时它不会引起问题,而且我不知道为什么中间的这些值不会像下面那样更改为 1其他。
最佳答案
您无法访问未初始化的对象。 malloc
不会初始化已分配数组的值,因此您无法打印它们。这样做会导致未定义的行为。
其次,您有 N
个元素,因此您需要
for (i = 0; i < N; ++i)
在malloc
中需要N * sizeof(int)
,而在遍历数组时需要N
,这是因为malloc与数据类型无关并处理内存字节,但变量 pointer
具有数据类型 int *
,因此它知道其元素是 int
关于c - 未使用指针正确初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257203/