tags:

views:

115

answers:

4

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...

+5  A: 

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.

rlbond
yeah...this worked..thanx
ravi
`*(a[0])` is fine too - `[]` has higher precedence than unary `*`.
caf
A: 
#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;
}
karlphillip
I guess this is it.
karlphillip
A: 

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.

harper
A: 

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);
} 
GreenMatt