附加到c中动态分配的数组
我尝试重新分配,但它不起作用,
这是代码。感谢您的帮助
trial = malloc (4 * sizeof(int));
trial[0] = 1; trial[1] = 4;trial[2] = 7;trial[3] = 11;
trial = (int*)realloc(trial, sizeof(int) * 5);
trial[sizeof(trial)-1] = 23;
int a;
for(a = 0; a < sizeof(trial); a++){
printf("TRIAL %d \n", trial[a]);
}
输出看起来像这样
TRIAL 1
TRIAL 4
TRIAL 7
TRIAL 23
它应该是
TRIAL 1
TRIAL 4
TRIAL 7
TRIAL 11
TRIAL 23
I try realloc but it didn't work
this is the code. thanks for your help
trial = malloc (4 * sizeof(int));
trial[0] = 1; trial[1] = 4;trial[2] = 7;trial[3] = 11;
trial = (int*)realloc(trial, sizeof(int) * 5);
trial[sizeof(trial)-1] = 23;
int a;
for(a = 0; a < sizeof(trial); a++){
printf("TRIAL %d \n", trial[a]);
}
And the output look like this
TRIAL 1
TRIAL 4
TRIAL 7
TRIAL 23
It should be
TRIAL 1
TRIAL 4
TRIAL 7
TRIAL 11
TRIAL 23
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
问题是
sizeof
并没有告诉你数组中有多少个元素;它告诉您指针(指向第一个元素)占用了多少空间。所以sizeof(Trial) == sizeof(int*)
,而不是元素的数量。您需要单独存储长度。The problem is that
sizeof
does not tell you how many elements are in the array; it tells you how much space the pointer (which points to the first element) takes up. Sosizeof(trial) == sizeof(int*)
, and not the number of elements. You need to store the length separately.sizeof 将返回 sizeof(int *),这是指针的大小。您必须单独跟踪指针的大小。
另外,您不应该将 realloc() 返回到您正在重新分配的指针。如果 realloc 返回 NULL,它不会修改指针,并且您将丢失它。最好使用临时指针,如下所示:
sizeof will return sizeof(int *), which is the size of the pointer. You will have to keep track of the size of the pointer seperately.
Also, you should not return realloc() to the pointer you are reallocating. If realloc returns NULL, it will not modify the pointer and you will lose it. It is best to use a temporary pointer as follows:
动态分配的内存上的
sizeof()
仅返回类型的大小,而不是分配的块的大小。因此,在本例中,sizeof(Trial)
将返回 4,即int*
的大小。sizeof()
on dynamically allocated memory only returns the size of the type, not the size of the block allocated. Sosizeof(trial)
in this case will return 4, the size of anint*
.sizeof(Trial)
== 一个常量(可能是 4 或 8)。它不会是您分配的元素的数量。你需要类似的东西
sizeof(trial)
== a constant (probably 4 or 8). It won't be the count of elements you allocated.You need something like
sizeof 返回类型的大小,在本例中是 int * 的大小,我假设它是 4 个字节。因此,您将数组大小设为 5,但将元素 (4 - 1) 设置为 23。您需要通过变量来跟踪数组的大小。
sizeof returns the size of the type, in this case the size of an int * which I assume is 4 bytes. So you are making the array size 5, but you are setting element (4 - 1) to 23. You'll need to keep track of the size of the array through a variable.