-2

I am learning pointers and going through the examples from this Stanford PDF Stanford Pointers Guide

I decided to write some code using their examples to get a better handle on what is happening. I am working from page 21 of the PDF.

When I run the code I get a segmentation fault, so I know that I'm trying to access memory that doesn't belong to me, but I don't understand where I'm going wrong.

Here is the code I have written:

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

// function prototypes
void C();
void B();

void main(){
    int *worthRef;
    int num = 42;
    worthRef = &num;
    B(*worthRef);
} 

// Takes value of interest by reference and adds 2
void C(int* worthRef){
    *worthRef = *worthRef + 2;
    printf("num = %d", &worthRef);
}

// adds 1 to value of interest then calls C()
void B(int* worthRef){
*worthRef = *worthRef + 1;  // add 1 to worthRef as before

C(worthRef);    // NOTE: no & required. We already have a pointer to 
        // the value of interest, so it can be 
        // passed through directly
}
Ross Satchell
  • 341
  • 4
  • 14
  • 2
    [`void main` is wrong](http://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c?rq=1). – melpomene Aug 20 '16 at 18:14
  • 1
    Your function prototype `void B();` doesn't tell the compiler what (type) the argument(s) is/are. It should be `void B(int* worthRef);` – Weather Vane Aug 20 '16 at 18:16
  • 3
    `B(*worthRef);` ==> `B(worthRef);` – WhozCraig Aug 20 '16 at 18:17
  • `void main()` is also an invalid signature. Before starting with pointers, learn about functions, how to declare them, etc. Then enable all recommended warnings and pay heed to them. Resolove all warnings (learn what they mean! before asking others for help! – too honest for this site Aug 20 '16 at 18:31

1 Answers1

4
// function prototypes
void C();
void B();

That comment is a lie. Those are function declarations without a prototype (which is part of the problem in this code).

    B(*worthRef);

This line calls B with an int. (Given the declaration int *worthRef, the type of *worthRef is int.)

void B(int* worthRef){

But here B expects to be given a pointer to an int, which is the bug: You're passing a number where a pointer is expected.


To fix this, change the call in main to B(worthRef) (or B(&num)), and change

    printf("num = %d", &worthRef);

to

    printf("num = %d\n", *worthRef);

If you had included a prototype in your function declarations, then the compiler would have warned you about the problem (probably):

// function prototypes
void C(int *);
void B(int *);
melpomene
  • 84,125
  • 8
  • 85
  • 148