[英]convert int to pointer int *ptr position;
i have 5 digits in 1 pointer我在 1 个指针中有 5 个数字
int* reversevec(int* ptr, unsigned int Ne){
int* ReverResult;
unsigned int rever=Ne, z;
ReverResult=(int*)malloc(Ne*sizeof(int));
for (int i = 0; i < Ne; ++i)
{
z=*(ptr+rever);
printf("%i ",z);//to be sure z starts from the last number on ptr to the fisrt
rever--;
}
return ReverResult;
}
example Number of elements(Ne)=5示例元素数(Ne)=5
int* ptr have 5 numbers {1 2 3 4 5} int* ptr 有 5 个数字 {1 2 3 4 5}
every time when z is printed i got {5 4 3 2 1}每次打印 z 时,我都会得到 {5 4 3 2 1}
but i cant save z into *ReverResult但我无法将 z 保存到 *ReverResult
ReverResult=(z+rever);
this line is what i tried to put into cicle for to save z and position into int pointer ReverResult but i cant convert int to int*;
这条线是我试图放入 cicle 以将 z 和位置保存到 int 指针 ReverResult 中的内容,但我无法将 int 转换为 int*;
There are many problems here这里有很多问题
z
is a local variable int. z
是局部变量 int。 its address will not be useful to return, because it will be out of scope.返回它的地址将没有用,因为它将超出范围。 returning an offset from its address is even worse, since that is a totally unrelated place in memory.
从其地址返回偏移量甚至更糟,因为那是内存中完全不相关的地方。
you also have an off-by-one error.你也有一个一对一的错误。 imagine Number elements is one.
想象数字元素是一。 You will then try to view ptr+1 instead of ptr+0.
然后您将尝试查看 ptr+1 而不是 ptr+0。
you've also tagged this c++ but are writing c style code.你也标记了这个 c++ 但正在编写 c 风格的代码。
to answer your primary question, rather than writing ReverResult=(z+rever)
one could write *(ReverResult + rever - 1) = *(ptr + i)
回答你的主要问题,而不是写
ReverResult=(z+rever)
可以写*(ReverResult + rever - 1) = *(ptr + i)
The other way round, you need to dereference your pointer to be able to assign.反过来,您需要取消引用您的指针才能进行分配。 After all, you are easier off with pure pointer arithmetics:
毕竟,使用纯指针算术更容易:
int* result = malloc(sizeof(*ptr) * ne);
// let's just have to pointers running through the two arrays:
for(int* p = ptr + ne, *r = result; p-- != ptr; ++r)
{
*r = *p;
// ^ ^ this is the important part: dereference both pointers
}
If you still prefer indices you can use operator[]
:如果您仍然喜欢索引,您可以使用
operator[]
:
--ne; // so that we don't have to subtract within the loop again and again
for(size_t index = 0; index <= ne; ++index)
{
result[index] = ptr[ne - index];
// ^^^^^^^ again: dereferencing, this time with offset
}
array[index]
is entirely equivalent to *(array + index)
– and actually it, too, to index[array]
(eg 7[array]
), which is often used to fool the inexperienced... array[index]
完全等同于*(array + index)
– 实际上它也等同于index[array]
(例如7[array]
),这通常用于愚弄没有经验的人...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.