0

I have a below code in C:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    typedef struct sample { 
        int num;        
    } abc;

    typedef struct exmp{        
        abc *n1;        
    } ccc;

    abc *foo;
    foo = (abc*)malloc(sizeof(foo));
    ccc tmp;
    tmp.n1 = foo;

    ccc stack[10];

    stack[0] = tmp;
    printf("address of tmp is %p\n",&tmp);
    // need to print address contained in stack[0]

    return 0;
}

In the above code I want to check if the address at stack[0] is same as address of tmp. How do I print address at stack[0] as I printed out tmp's address?

Arnold
  • 185
  • 1
  • 2
  • 8

1 Answers1

5

It's very simple, just do this

printf("address of tmp is %p and address of stack[0] %p\n",
    (void *)&tmp, (void *)&stack[0]);

and actually this will work

printf("address of tmp is %p and address of stack[0] %p\n", 
    (void *)&tmp, (void *)stack);

Also, Do not cast malloc(), and always check that the returned value is not NULL, i.e. that it's a valid pointer.

Community
  • 1
  • 1
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • 1
    &stack[0] gives the address of stack[0] itself , is it the same as address stored at stack[0]? – Arnold Feb 14 '15 at 08:16
  • I don't understand your question, can you explain more? – Iharob Al Asimi Feb 14 '15 at 08:20
  • Suppose , int var; int stack[4]; stack[0]=var .I meant does &stack[0] gives the address of stack[0] or address of var? In the above question I am expecting stack[0] to have address of tmp( var ). – Arnold Feb 14 '15 at 08:27
  • in `stack[0] = var` the value is copied, so `&stack[0]` will always give the address if `stack[0]`. In fact you can't change the address of an array, at least I don't know of any way to do it. – Iharob Al Asimi Feb 14 '15 at 08:29
  • [`%p` requires an argument of type `void*`](http://www.stackoverflow.com/questions/24867814/printfp-and-casting-to-void) . So cast the arguments of `printf` to `void*` – Spikatrix Feb 14 '15 at 08:35
  • @CoolGuy to make it complain on `gcc` I needed `-pedantic` but since it did complain I am going to change it. – Iharob Al Asimi Feb 14 '15 at 08:39