-3

I'm learning referencing in C and here is my code:

#include <stdio.h>

int main(void)
{
    int x = 5;

    int &ref = x;

    printf("%d\n", x);
    printf("%p\n", &x);     
    printf("%p\n", &ref);

    return 0;
}

When i compile, it shows these errors:

reference.c:7:6: error: expected identifier or '('

int &ref = x;

reference.c:11:18: error: use of undeclared identifier 'ref'

printf("%p\n", &ref);

2 errors generated.

What should i do to fix this and thanks in advance.

Thomas D
  • 93
  • 6

2 Answers2

4

c does not have a reference type, you can only use point instead of ref.

#include <stdio.h>

int main(void) {
    int x = 5;

    int *ref = &x;

    printf("%d\n", x);
    printf("%p\n", &x);
    printf("%p\n", &ref);

    return 0;
}
sundb
  • 490
  • 2
  • 8
  • Small point, it is better to put the star next to the identifier name, because in the case of say `int* ref, point;` the variable `point` is *not* a pointer. The `*` modifies the following variable, not the preceding type. – Weather Vane Dec 27 '18 at 11:09
  • @WeatherVane or you could avoid declaring multiple pointers in one declaration and not have that problem. There's nothing wrong with `int* ref` – M.M Dec 27 '18 at 11:10
  • @WeatherVane i fix it, ths – sundb Dec 27 '18 at 11:11
  • @M.M true and it's been edited. – Weather Vane Dec 27 '18 at 11:11
  • @M.M Although I also like to put * in front, but redis, nginx are placed behind – sundb Dec 27 '18 at 11:12
2

A "reference" in C is called a pointer. Through the pointer you reference something. In your code you need to write:

#include <stdio.h>

int main(void)
{
    int x = 5;

    int *ref = &x;           // now ref points to x

    printf("%d\n", x);       // print the value of x
    printf("%p\n", &x);      // print the address of x
    printf("%p\n", &ref);    // print the address of the pointer variable
    printf("%d\n", *ref);    // print the value of the int that ref is pointing to
    return 0;
}
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • thanks. I was reading the concept of a pointer and the code is in C++ so I translated them into c since they are similar (I'm learning c as my first language). Apparently, c++ has references but c does not. – Thomas D Dec 27 '18 at 12:12
  • Calling a pointer in C a "reference" is confusing, since in C++ a reference is different than a pointer. But you would be right in saying that a pointer can often do the same job as a reference – HAL9000 Dec 27 '18 at 13:45