简体   繁体   中英

Arrays of pointers in C

Hii ,

I have written the following code to improve it for the higher datastructures .

 #include<stdio.h> #include<stdlib.h> #include<malloc.h> int display(int *a , int *b , int *c) { a[0] = b; a[1] = c; printf("\\n%d %d",a[0],a[1]); ------- point 1 printf("\\n %d %d",*(a[0]),*(a[1])); ------- point 2 return 1; } int main() { int *a[5]; int b,c; scanf("%d %d",&b,&c); printf("%d %d",b,c); display(a,&b,&c); getchar(); } 

I get the addresses in point 1 , but i dont get the values in point 2....What have i done wrong ... If my program itself is wrong , please jus give me a sample code that can dereference an array of pointers to get the value pointed by the element of array...

This code shouldn't compile. The signature for display should be int display(int **a , int *b , int *c) , because a is a pointer to int* (remember that arrays degrade to pointers). Then, you need to write printf("\\n%d %d",*a[0],*a[1]) to dereference the pointers in the array.

#include <stdio.h>

int display(int** a, int* b, int* c)
{
   // store the value of b and c on array a
    a[0] = b; 
    a[1] = c;

    //print the memory addresses stored in hex format
    printf("0x%x 0x%x\n", (int)a[0], (int)a[1]);

    //print the values
    printf("%d %d\n", *a[0], *a[1]);

    return 1;
}

int main()
{
    int* a[5];
    int b,c;
    scanf("%d %d",&b,&c);
    printf("%d %d\n",b,c);
    display(a,&b,&c);
    getchar();

    return 0;
}

The signature of display() indicates that a is a pointer. In theory, this might work in C, but gcc gave me an error. What you want to tell the compiler is that you want an array of pointers. I accomplished this with int **a in the function signature. The code below shows how I did this. Also, I cleaned it up a bit, since some of your includes aren't needed, the pointers should be printed as unsigned, display would probably be better as a void, having the "\\n" at the beginning of the line was irritating in that the last line of output ended up on my prompt line, and the getchar() serves no real purpose here.

#include<stdio.h>

void display(int **a , int *b , int *c)
{
  a[0] = b;
  a[1] = c;
  printf("%u %u\n", a[0], a[1]);
  printf("%d %d\n", *a[0], *a[1]);
} 

int main(void)
{
  int *a[5];
  int b,c;
  printf("Enter two integers: ");
  scanf("%d %d",&b,&c);
  printf("%d %d\n",b,c);
  display(a,&b,&c);
} 

You want store addresses (pointers) in the vector a. Define your function to accept a vector of pointers:

int display(int *a , int *b , int *c)

This has the advantage that the compiler compiles the code.

Or better: use names that help to remember what you mean.

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