-3

I was recently reviewing an excellent, highly praised article on pointers: What are the barriers to understanding pointers and what can be done to overcome them? As I read through it, I came to understand what pointers are. Unfortunately, I'm still unable to use them.

Here's why: I don't understand the naming! Or the applications, really, of pointers. After reading through several 'so-you-want-to-learn-c' books and articles, I've encountered similar code, time and again: "how to create and instantiate a pointer".

When answering, please use example code to demonstrate what, in practice, pointers output.

Here's the code:

char ch = 'c'; 
char *chptr = &ch;

Or, perhaps more confusing:

char ch = 'c';
char *chptr;
chptr = &ch;

Notice that chptr is differently named from the other two variables, which are named ch. Why not name all three variables ch? What problem does it solve to give the pointer a different name?

Also, in the first block of code we have ...*chptr = &ch;; in the second, chptr = &ch;. What is making it acceptable to drop the asterisk in the second block?

Next, I wonder what the applications of pointers are. Do I always need a pointer (when do I need one and when do I not need one)? After submitting my answer, I feel confident--believing that I will be able to comprehend more complex code that uses pointers--enough to continue adapting the language intuitively. I'm still riddled with curiosity, though.

Take this block of code, for example:

typdef struct person
{
  char *name;
  int age;
}

Why declare the name as a pointer to a name variable that doesn't exist, and why declare the age variable as an int without using pointers? That wouldn't make sense, due to this block:

int main()
{
/* below, the int is a pointer */
  int *p;
  void *up;
  return 0;
}

Or this block:

char *sp;
sp = "Hello";
printf("%s",sp);

I thought pointers pointed to an address. "Hello" isn't an address.

With the two prior blocks in mind, have a look at this final block:

int main()
{
  int i,j;
  int *p;
  i = 5;
  p = &i;
  j = *p; //j = i?
  &p = 7; //i = 7?
}

Shouldn't j be set to &i because *p = &i not i. And shouldn't &p = 7 set the address of p to 7, which may not be i?

Community
  • 1
  • 1
Wolfpack'08
  • 3,982
  • 11
  • 46
  • 78
  • The last block of code is particularly confusing and important. I think that commenting the line, `p = &i;` might help. – Wolfpack'08 Dec 07 '12 at 03:56
  • You need to look at more code involving pointers, analyze it and try to modify it yourself. For me it worked much better than just reading any guide to pointers. – ljedrz Dec 07 '12 at 06:28
  • If you don't know what to do, downvote, vote to close, and leave no explanation. – Wolfpack'08 Dec 07 '12 at 08:51
  • @yzb3 No, that doesn't help. Does looking at a car with an engine and modifying how you drive tell you how the engine works? I've been studying C for years. There are multiple possible explanations for the things that are happening, and I need to see pointers for what they themselves are. I need a guide that uses real code, which is why I asked a question with code that I believe can make pointers abundantly clear for even absolute beginners, when explained. Not knowing a basic concept and understanding more advanced concepts is common. It's called 'false beginnerism'. 'Going back' to school. – Wolfpack'08 Dec 07 '12 at 10:03
  • 1
    But all of the examples you provided are extremely basic. Questions like `Notice that chptr is differently named from the other two variables, which are named ch. Why not name all three variables ch?` or code like `&p = 7;` indicate that you have not even tried to compile any code. If I was to point you to a simple book on C, I'd go with C Primer Plus by Stephen Prata. And I wouldn't skip the chapters before pointers, because you need to familiarize yourself with regular variables first. – ljedrz Dec 07 '12 at 17:51
  • Yzb3 yes. Usually false beginners need to have beginner questions answered to cement foundational understanding. They're basic, but the answers are either hard to provide or very difficult to understand. – Wolfpack'08 Dec 07 '12 at 22:45
  • Since `&p` in `&p = 7;` is not a modifiable l-value, the code quoted shouldn't compile. `&p` is the address of variable `p` and is of type `int **`. – Jonathan Leffler Dec 08 '12 at 22:49
  • Bs this isn't constructive. This is by far the most constructive pointers question on so. Please nominate for reopening – Wolfpack'08 Dec 10 '12 at 12:45
  • I think this is a perfectly good question, - I'm struggling with the syntax issues you pointed out. While I do understand the concept of pointers, and why they're very useful, parsing the appearingly conflicting syntax is killing me. I just don't get it. – Fred Hamilton Jan 26 '15 at 02:06

2 Answers2

2

Notice that chptr is differently named--at this point I added an answer--from the other two variables, which are named ch. Why not name all three variables ch?

  • it is common practice for pointers to be prefixed by 'p' (or in this case suffixed by 'ptr') so that it is clear to the code reader that the variable is a pointer. As you now know, programming with pointers is initially tough, and while int *i = 1; and int i = 1 are both legal, unintentionally substituting one for the other may cause some serious debugging time.

Also, in the first block of code we have ...*chptr = &ch;; in the second, chptr = &ch;. What is making it acceptable to drop the asterisk in the second block?

  • it is the syntax to use a '*' to declare a pointer variable, ex: int *pInt;
  • to assign a value to the pointer variable (to make it point to something), you don't need the '*'. ex:

        int *pInt;
        pInt = &someInt;
    
  • however, to assign a value to the address pointed to by the pointer variable or to get the value of the pointed to by the variable, you have to dereference it using the '*'

        int *pInt;
        int someInt = 100;
        pInt = &someInt;
        *pInt = 50;
        printf("%d - %d", *pInt, someInt); // prints "50 - 50"
    

Next, I wonder what the applications of pointers are.

  • pointers are used for, among others :

    1. pass-by-value to a function
    2. dynamic memory allocations ...

Why declare the name as a pointer to a name variable that doesn't exist, and why declare the age variable as an int without using pointers?

  • "Hello" is an array of 5 characters. using sp = "Hello", "Hello" is stored in a memory location, and it's address is assigned to sp.
  • From your example, I assume that name may contain any number of characters so during the execution of the program, a dynamic allocation will be used to store the name.

I thought pointers pointed to an address. "Hello" isn't an address.

  • "Hello" (character strings in C) are treated as an array of characters. in this case, sp points to a memory location (heap or stack) that contains an array of 5 characters, and when you use it in an assignment, it will return the address of the "Hello" string in memory.

    int main()
    {
      int i,j;
      int *p;
      i = 5;
      p = &i;
      j = *p; //j = i?
      &p = 7; //i = 7?
    }
    
    • j is not i, in the sense that changing j=100 will not affect the value of i (i still has value 5).

    • &p = 7 is not probably what you intended. it will probably cause an error since &p will yield a value, and it is illegal to assign a value to a value (example: it will evaluate to something like this: 0x0108 = 7;)

    • consider the following memory sample for the above vars

       address | var    | value
       0x0100  | i      | undefined
       0x0104  | j      | undefined
       0x0108  | p      | undefined
      
    • after j = *p,

       0x0100 | i      | 5
       0x0104 | j      | 5
       0x0108 | p      | 0x0100
      

after *p=7 (corrected from &p = 7;)

         0x0100 | i      | 7
         0x0104 | j      | 5
         0x0108 | p      | 0x0100
Ronaldo Nazarea
  • 356
  • 1
  • 7
1
Example code:

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

int main()
{
    int i;
    long j;
    int *p;

    i = 5;
    p = &i;  ---> Assigning address of "i" to p, so that pointer p points to "i"
                  By dereferencing pointer "p" i.e. by *p, shall retrieve value "5". 

    j = *p; or j = i (alternative to assign value "5" to "j")

    printf("Value of j:%d \n", j); --> Output is "5".

    &p = 7; //i = 7? --> will not change the value of "i" to 7, but instead  
                         will try to change the address of "p", which cannot be 
                         modified.                              

    j = (long)&i;  ---> Assigns address of "i" i.e "100" to "j". 

    printf("Value of j:%p \n", j); --> Output is address of "i" i.e. "100"

    printf("Value of i:%d \n", i); --> Output is "5". Value assigned to "i".

    printf("Address of i:%p \n", &i); --> Output is "100" i.e. address of "i" in our
                                          case.

    printf("Value of *p:%d \n", *p); --> Output is "5". Since pointer p is pointing 
                                        to "i" i.e. "100" in our case. 
                                        *p -> by dereferencing, retrieves value 
                                        present at the address "100" 
                                        that would be "5".

    printf("Value of p:%p \n", p); --> Output is "100". Pointer p is pointing 
                                       to "i" i.e. "p = &i" it will be "100" in our 
                                       case.   

    printf("Address of p:%p \n", &p); --> Output would be the address of pointer "p".
                                          It will not be same as the address of "&i" 
                                          or value present in "p".

    return 0;       
}
Gautham Kantharaju
  • 1,735
  • 1
  • 21
  • 24
  • What does get relate to in code? What does get/holds do in code? For example, `printf("%s",*p);`? If you can show these things using print statements, would you please do so? Alternatively, may I test it and add an edit? – Wolfpack'08 Dec 07 '12 at 10:17
  • Wolfpack'08: I have coded and executed the program on 64bit machine, so I declared "j" as "long" instead of "int or unsigned". Because in 64bit machine sizeof(int) is 4bytes but sizeof(pointer/long) is 8bytes. Since I am assigning address to "j" I had to declare it has long. – Gautham Kantharaju Dec 07 '12 at 11:57
  • Does dereferencing simply mean removing the asterisk, the pointer identifier, from before the pointer variable? If i also equals five, I wonder why the busy work needs to be done apart from that the opposite of what I assume to be dereferencing gives the address, which is useful. – Wolfpack'08 Dec 07 '12 at 12:33
  • The opposite of dereferencing is probably referencing. – Wolfpack'08 Dec 07 '12 at 12:34
  • Dereferencing is nothing but accessing the value present at that address to which the pointer "p" is pointing to i.e. done by "*p". Referencing means "p = &i" reference to memory location i.e. address of "i". A pointer references a location in memory, and obtaining the value at the location a pointer is known as dereferencing the pointer. – Gautham Kantharaju Dec 08 '12 at 15:51
  • It's a really good answer.The structure or rather order, confused me at first. Need to rework some grammar, but maybe a good enough answer to accept. – Wolfpack'08 Dec 10 '12 at 12:47