Home > Software engineering >  convert int to pointer int *ptr position;
convert int to pointer int *ptr position;

Time:10-15

i have 5 digits in 1 pointer

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

int* ptr have 5 numbers {1 2 3 4 5}

every time when z is printed i got {5 4 3 2 1}

but i cant save z into *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*;

CodePudding user response:

There are many problems here

z is a local variable 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.

you've also tagged this c but are writing c style code.

to answer your primary question, rather than writing ReverResult=(z rever) one could write *(ReverResult rever - 1) = *(ptr i)

CodePudding user response:

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[]:

--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] (e. g. 7[array]), which is often used to fool the inexperienced...

  •  Tags:  
  • c
  • Related