简体   繁体   中英

Changing the value of a pointer but keeping the address

I want to write a program which changes the value in the address a pointer points to but keep the address the same. I wrote a small program to test it but I'm having some problems.

#include <stdio.h>

void swap(int *entry1, int *entry2, int length)

{
  int i,temp;

  for(i=0; i<length; i++)
    {
      temp = *entry1[i];
      *entry1[i] = *entry2[i];
      *entry2[i] = temp;
    }
}

int main()

{
  int length=5, i;

  int *entry1 = malloc(length * sizeof(int));
  int *entry2 = malloc(length * sizeof(int));

  for(i=0;i<length;i++)
    {
      entry1[i] = i + 1;
      entry2[i] = length - i;

    }
swap(entry1, entry2, length);

return 0;
}

I was under the impression that I could use an asterisk to access the value at stored in the address the pointer points at. However, when I run this code I get the error:

error: invalid type argument of unary ‘*’ (have ‘int’)

I believe if I do:

temp = entry1[i];
entry1[i] = entry2[i];
entry2[i] = temp;

This would effectively swap the values, however, it would also swap the address' which I don't want.

Well yes you did wrong. Correct one would be

  temp = entry1[i];
  entry1[i] = entry2[i];
  entry2[i] = temp;

This would be enough given that array decays into pointer to first element - enabling you to change the value of the array.

invalid type argument of unary ‘*’ (have ‘int’) 

The error itself says that you are trying to dereference an int not an address or some pointer value.

And for your information, entry1[i] is *(entry+i) . But you did this **(entry+i) . You passed a single level pointer so it is expected that you won't dereference it twice without any error.


Also check the return value of malloc and free dynamically allocated memory when you are done working with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM