使用指向数组的 void 指针
我只是想使用一个指向整数数组的 void 指针,我试图看看是否可以通过将其转换回 int 来打印该数组。但它给了我一些随机值。你能告诉我哪里错了吗?
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[5];
int x;
int j;
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
void *arr=a;
for(j=0;j<4;j++){
x = *(int *)(arr+j);
printf("%d",x);
}
return 0;
}
输出是这样的:
133554432131072512
为什么它不打印数组 a[] 的元素,即 1,2,3,4 ?
I was just trying to use a void pointer to an integer array ,I tried to see if i can print the array back by casting it back into int. But it is giving me some random value. Can you tell me where i am going wrong?
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[5];
int x;
int j;
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
void *arr=a;
for(j=0;j<4;j++){
x = *(int *)(arr+j);
printf("%d",x);
}
return 0;
}
Output is this:
133554432131072512
Why is it not pinting elements of array a[] i.e 1,2,3,4 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要在添加
j
之前先转换arr
。这是一个最小的修复:但我认为这样写更清楚:
You need to cast
arr
before addingj
. Here is a minimal fix:but I think it's clearer to write:
您正在对
void *
进行指针算术,这在 C 中无效。在 GNU C(带有 gcc 扩展的 C)中,它实际上是允许的,并且
sizeof (void)
是被认为是 1。http://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html
You are doing pointer arithmetic on
void *
which is not valid in C.In GNU C (C with gcc extensions), it is actually permitted and the
sizeof (void)
is considered to be 1.http://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html
C 标准没有定义
void *
算术的行为,因此在进行算术之前,您需要将void *
转换为另一个指针类型first与它。一些编译器[作为扩展]将
void *
的指针算术视为与char *
相同,因此每个'+1'只会将地址增加1,而不是增加所指向对象的大小。但这不是标准化的,因此您不能依赖这种行为。The C standard does not define behaviour for arithmetic of
void *
, so you need to cast yourvoid *
to another pointer type first before doing arithmetic with it.Some compilers [as an extension] treat pointer arithmetic of
void *
the same aschar *
, so each ‘+1’ will only increase the address by 1, rather than by the size of the pointed-to object. This is not standardised though so you can't rely on this behaviour.您不应该向 void 指针添加数字。之前施放它。 (
x = *((int *)arr+j);
)当您向指针添加数字时,编译器会将此数字乘以所指向类型的大小,因此如果您添加数字指向错误类型的指针,您将得到错误的结果。
如果我没记错的话,添加到 void* 是非法的,但有些编译器会添加确切的字节数(就像 char* 一样)。
`
you should not add numbers to void pointers. cast it before. (
x = *((int *)arr+j);
)When you add number to a pointer, the compiler multiply this number with the size of the type that is pointed, so if you add number to a pointer to wrong type, you will get wrong result.
if I remember correct, add to void* is illegal, but some compilers adds the exact number in bytes (like it is char*).
`