1

To get a better grasp of pointers for this problem set, I watched a non-cs50 video on pointers, which showed the following basic code:

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

int main ()
{
int p = 10;
int *pointer = p;
printf("the addres of the pointer p is %u", &pointer);

return 0;
}

In the Youtube, this code compiled and printed out the memory address. Nonetheless, I am getting an error:

"incompatible integer to pointer conversion initializing 'int *' with an expression of type 'int'; take the address with &
      [-Werror,-Wint-conversion]"

Why is this not working in my system?

1 Answer 1

1

I'm a little suspicious of whether it worked, or maybe they are using a different, more forgiving, compiler or compile settings, or maybe c++. There are a couple issues. First, int *pointer = p; tries to assign the contents of p to an address pointer. Instead it should assign the address of p, using the & modifier.

Second, there's a type mismatch in the print statement. You need to use a pointer type formatter to print an address.

Try the following instead:

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

int main ()
{
    int p = 10;
    int *pointer = &p;
    printf("the addres of the pointer p is %p \n", pointer);
    return 0;
}

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Thanks Cliff. From your code, I understand that a pointer (*pointer) should point to an address (&p). However, in the lecture of week 5, David writes code for a node as: node *ptr = list. Why does this work? Shouldn't *ptr be assigned to a value like &list?
    – Haim
    Commented Jun 25, 2017 at 16:09
  • This is a new reply to an old comment that I missed. Keep in mind that I have not seen (or don't remember seeing) the specific video. Having said that, Prof. Malan was clearly discussing the speller problem set and linked lists. It's almost certain that list is also declared as a pointer to a node structure. It is perfectly correct to copy the address stored in one pointer var to another pointer var using something like a = b; when both a and b are declared as pointers to the same data types or the same struct types.
    – Cliff B
    Commented May 23, 2023 at 3:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .