0

I am a new to programming, in book i find this: Operator '&'- Returns the address of a variable. &a; returns the actual address of the variable. Ok. But why i can't do this (in commented lines)?

#include <stdio.h>
#include <string.h>

int main(){

        char a = 'A';
        //int i;

        printf("char a is: %c\n",a);

        //i=&a;
        //printf("adrress  of a is: %d\n",i);
}

When compilling i get an error. What is wrong?

Cœur
  • 32,421
  • 21
  • 173
  • 232
Madriot
  • 58
  • 5
  • 2
    `%p` is the *format specifier* for printing a *pointer* (the address), e.g. `printf("char a is: %p\n",(void *)&a);` – David C. Rankin Oct 25 '17 at 06:27
  • 1
    Because `i` is an `int` type, not a pointer type. Suppose the size of `int` is 4 and the size of a pointer is 8. Can you see a problem? – Weather Vane Oct 25 '17 at 06:32
  • yes it's work, thank you! i need read more about pointers, sorry for stupid question) – Madriot Oct 25 '17 at 06:32

2 Answers2

1

Continuing from my comment, %p is the proper format specifier for printing a pointer (e.g. address). You can simply rewrite your printf as:

printf ("char a is: %p\n", (void*)&a);

Also, get in the habit of using the correct declaration for main. It is either int main (void) or int main (int argc, char *argv[]). main is also type int and therefore should return a value (the standard defines EXIT_SUCCESS (0) or EXIT_FAILURE (1), See: C11 Standard §5.1.2.2.1 Program startup (draft n1570). See also: See What should main() return in C and C++?, e.g.

#include <stdio.h>

int main (void) {

    char a = 'A';

    printf ("char a is: %p\n", (void*)&a);

    return 0;
}

Example Use/Output

$ ./bin/prnaddr
char a is: 0x7fffa7f84f70

Let me know if you have further questions.

David C. Rankin
  • 69,681
  • 6
  • 44
  • 72
  • Thanks for detailed explanation! – Madriot Oct 25 '17 at 06:36
  • Sure, also note, the cast to `(void*)` isn't technically necessary when printing a direct address (e.g. `&a`), but is included to emphasize the `type` for the format specifier `%p` is `(void*)` `:)` – David C. Rankin Oct 25 '17 at 06:40
0
#include <stdio.h>
#include <string.h>

int main()
{
        char a = 'A';
        char* i = &a;
        printf("char a is: %c\n", a);
        printf("address of a is: %p\n", &a);
        printf("address of a is: %p\n", i);
        printf("char is: %c\n", *i);
}

a is a char variable with 'A' value. Address of a is &a. char* i is a pointer which points to a. To get value by pointer * is used

Gor Asatryan
  • 829
  • 6
  • 20