Help with simple pointer program

  • Thread starter leroyjenkens
  • Start date
  • Tags
    Program
In summary: I have a class, but my professor is terrible and I really don't feel that I am learning anything from him. That's why I'm asking so many questions. I don't know where else to turn. I will try experimenting more with the code, but I really just don't understand pointers or how this specific program is supposed to work. I'm sorry if I'm asking too many questions, I really am trying to understand.
  • #1
leroyjenkens
616
49
Hello, I wrote this program but it's not working. Here's what the program is supposed to do:

"Write a program that reads data into a and b using the pointers x and y. The program then multiplies the value of a by b and stores the results in c using the pointers x, y, and z. Finally, it prints all three variables using the pointers x, y, and z."

Mine let's me type in two numbers, but it returns the number 2 every time. I'm not sure why.

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

int main()
{
   int c;
   int b;
   int a;
   int* x = a;
   int* p = b;
   int** y = p;
   int* q = c;
   int** r = q;
   int*** z = r;
   print (&x, &y);
}
void print (int* x, int** y)
{
    scanf("%d %d", &x, &y);

    return *x * **y;
}
 
Technology news on Phys.org
  • #2
leroyjenkens said:
Hello, I wrote this program but it's not working. Here's what the program is supposed to do:

"Write a program that reads data into a and b using the pointers x and y. The program then multiplies the value of a by b and stores the results in c using the pointers x, y, and z. Finally, it prints all three variables using the pointers x, y, and z."

Mine let's me type in two numbers, but it returns the number 2 every time. I'm not sure why.

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

int main()
{
   int c;
   int b;
   int a;
   int* x = a;
   int* p = b;
   int** y = p;
   int* q = c;
   int** r = q;
   int*** z = r;
   print (&x, &y);
}
void print (int* x, int** y)
{
    scanf("%d %d", &x, &y);

    return *x * **y;
}

You should get rid of your print function, as it isn't required in this problem. You can do everything in main in this problem. Other problems with print:
1. You don't have a prototype for print.
2. You have print returning a value, but it is a void function.

General problems:
You have way more variables than you need, and the ones you have are much more complicated than necessary, with double and triple indirection.

All you need are six variables: three int variables and three int * variables. You don't need any int ** or int *** variables.

Since you are using a, b, and c for your int variables, it might be useful to define the pointer variables as ptr_a, ptr_b, and ptr_c. That will reinforce the idea that these are pointers.

Here's how to read a value into a:
Code:
int a;
int * ptr_a = &a;
printf("Enter a value for a\n");
scanf("%d", ptr_a);
If you type 5 after the prompt, a's value will be 5. scanf stores the value 5 at the address pointed to by ptr_a.
 
  • #3
First,

I thought you were pirating half done sources and asking for help to finish them off and submit them as your own homework;

now, I may actually give you the benefit of doubt and speculate that you are trying to learn C "by yourself"...

then, again, you are asking too many too simple questions to the point that I am starting to feel "used" as a programming tutor...which I am not. Not to mention that, then, you are NOT learning "by yourself" when you keep asking question after question after question.

If you are going to try to learn programming "by yourself" I feel like you need to put a little more effort, your questions are too basic or simple to answer if you tried a couple more code combinations.

Anyway, that's me.

Hopefully (for you) other people will not feel the same and continue to answer your questions...but don't abuse the forum, you may end up putting more people off.

Good luck.
 
  • #4
gsal,
I believe that the OP is in a class. He said in another thread that the work was for an assignment to be handed in.

Leroy,
I don't know what programming environment you're using, but I'll bet that there is a debugger available for it. The best way to understand what your program is doing is to use a debugger to single step through it. With a debugger you can temporarily halt the program by inserting a breakpoint, and inspect the values of variables, and watch the effect on them when a line of code executes.

A debugger can help you understand how pointers work. An initialized pointer contains the address of some memory location, which may or may not be the same location as a variable in your program. You can change the value of a pointer (put a different address in it, meaning it now points somewhere else) or you can change the value of the location it's pointing to.
 
  • #5
gsal said:
First,

I thought you were pirating half done sources and asking for help to finish them off and submit them as your own homework;

now, I may actually give you the benefit of doubt and speculate that you are trying to learn C "by yourself"...

then, again, you are asking too many too simple questions to the point that I am starting to feel "used" as a programming tutor...which I am not. Not to mention that, then, you are NOT learning "by yourself" when you keep asking question after question after question.

If you are going to try to learn programming "by yourself" I feel like you need to put a little more effort, your questions are too basic or simple to answer if you tried a couple more code combinations.

Anyway, that's me.

Hopefully (for you) other people will not feel the same and continue to answer your questions...but don't abuse the forum, you may end up putting more people off.

Good luck.

Anything I have that I didn't write myself is taken from the book, which is allowed. What I have done so far on this program is completely mine.

I'm not trying to learn C by myself, I'm taking a required course for my physics degree. I'm just trying to get through this class with at least a C. I don't like programming and I never plan to touch the subject after this class, so I'm just trying to learn enough to get by. I need to do well on this project, which has 4 programs, and do decently on the final exam and I'm done forever with this.

I don't want anyone to feel used. If you feel that way, you're free to not respond at all if you think that's what I'm doing. I'm just desperate to get the hell out of this class and never look back.
General problems:
You have way more variables than you need, and the ones you have are much more complicated than necessary, with double and triple indirection.

All you need are six variables: three int variables and three int * variables. You don't need any int ** or int *** variables.
Oh, I didn't realize the question left out the other variables. The problem has a diagram that I can't include, so I left out the part of the question that says it wants the program to mimic the diagram. It shows z > r > q > c
Which means z is pointing to r which is pointing to q which is pointing to c.
It also has y > b > p and x > a.

Here's what I have so far. y points to p which points to b. What I've written stores the integer into b from p, but how do I store it from y to p to b?

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

int main()
{
   int c;
   int b;
   int a;
   int* x = &a;
   int* p = &b;
   int** y = &p;
   int* q = &c;
   int** r = &q;
   int*** z = &r;
    printf("Enter a value for a and b: ");
    scanf("%d %d", x, p);



    return a*b;
}

Thanks for the response.
 
  • #6
leroyjenkens said:
I'm just trying to get through this class with at least a C. I don't like programming and I never plan to touch the subject after this class ...

I'm just desperate to get the hell out of this class and never look back.
I wouldn't be so sure of that. I would guess that most working physicists write code in some language for simulations, so anything you learn in this class will be directly related to your actual job description as a working physicist.
leroyjenkens said:
Oh, I didn't realize the question left out the other variables. The problem has a diagram that I can't include, so I left out the part of the question that says it wants the program to mimic the diagram. It shows z > r > q > c
Which means z is pointing to r which is pointing to q which is pointing to c.
It also has y > b > p and x > a.
Don't you mean y -> p -> b? That's what you are saying below.
leroyjenkens said:
Here's what I have so far. y points to p which points to b. What I've written stores the integer into b from p, but how do I store it from y to p to b?

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

int main()
{
   int c;
   int b;
   int a;
   int* x = &a;
   int* p = &b;
   int** y = &p;
   int* q = &c;
   int** r = &q;
   int*** z = &r;
    printf("Enter a value for a and b: ");
    scanf("%d %d", x, p);



    return a*b;
}
What you have looks good, except for the last line. You're almost where you need to be, with all of your variables initialized correctly.

Now all you need to do is multiply a and b, and store the result in c. To get the values of a, b, and c, you need to use pointer dereferencing.

For a: Dereference x, as in *x.
For b: Dereference y twice, as in **y.
For c: Dereference z three times, as in ***z.

To see how this is working for a, suppose that a's value is 5 and that it is stored at location 100. After all variables are initialized, the value of x will be 100, and *x will be the value at location 100. Note that I am make these addresses up, but what I'm describing is the way things actually work.

IOW, x == 100 and *x == 5

To see how it's working for b, suppose that b's value is 15, and that it is stored at location 104. Suppose that p is stored at location 120. After initialization, we would see this:
y == 120
p == 104
b == 15

*y == 104, the value stored at p's location
**y == 15

Using similar analysis you can use z to get the value stored at c's location.
 
  • #7
With regard to what I said about working physicists writing code, you might post a question in the Career Guidance section under Science Education. I'm not a physicist, but you would be likely to get responses from people who are actually working in this field. In any case, programming experience would probably be a resume enhancer for many jobs in physics.
 
  • #8
I wouldn't be so sure of that. I would guess that most working physicists write code in some language for simulations, so anything you learn in this class will be directly related to your actual job description as a working physicist.
Maybe by then I'll be different. Right now my brain just refuses to understand this stuff and it makes me just want to get it over with.
I had a friend take this class last fall and he was constantly complaining about it. He said for some reason he just couldn't get it. I'd never experienced that before. Even things I didn't get eventually made sense to me. But now I know how he feels. I don't know what's wrong with me, but I can learn about loops, pointers, functions, and know exactly what they are and what they're for, but when it comes to applying it to a program, I'm like a deer in headlights. I open codeblocks and don't even know where to begin. It's frustrating.
My friend failed the class and had to retake it in the spring. I don't want that to happen to me.
Don't you mean y -> p -> b? That's what you are saying below.
Yeah that's what I meant, sorry.Well, I tried multiplying them together and this is what it says.

error: invalid operands to binary * (have 'int **' and 'int **')
Code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
   int c;
   int b;
   int a;
   int* x = &a;
   int* p = &b;
   int** y = &p;
   int* q = &c;
   int** r = &q;
   int*** z = &r;
    printf("Enter a value for a and b: ");
    scanf("%d %d", x, p);
   c = &x * &p
   printf("%d", c);    return;
}
 
  • #9
OK, the multiplication is a bit more complicated than I described. In my notes I neglect to write down the part where it say to store the product in c using x, y, and z.

Instead of doing c = a * b, you need to do this:

Code:
***z = *x + **y;

This is all too complicated to try to keep in your head, so in my notes I have drawn a diagram that shows the relationships between all of the variables. Along the top I have three boxes labeled a, b, and c.
Another box is labeled x, and has an arrow that points to a's box.
Two more boxes are labeled y and p. There's an arrow from the y box to the p box, and another arrow from the p box to the b box.
I also have boxes for z, r, and q, with arrows pointing to the appropriate locations.

The problem with your code is that you are trying to multiply things (addresses) for which multiplication is not defined. The only operations that are defined for pointers are increment, decrement, addition, and subtraction, and of course, dereferencing.

&x is the address of x, which is irrelevant here
&p is the address of p, which is what happens to be stored in y, but is no use if you're trying to get the value in b.

One final thing. Your main function returns a value (int main() ...), but you are just returning with that bare return statement at the bottom. You should change that to return 0;
 
  • #10
Why do I want to add x and y?

This problem is confusing. Here's what the first part says "Write a program that creates the structure shown in the figure below and reads data into a and b using the pointers x and y."

So I need to read data into a and b using the pointers x and y. What I did was read data into a and b using the pointers x and p, right? How do I go from using p to using y?
 
  • #11
leroyjenkens said:
Why do I want to add x and y?
You're not adding x and y. That's not what *x + **y means.

Here's a sketch of the drawing I did. It helps me keep things straight.
ptrs.PNG

x == the address of a
*x == the value stored at a
y == the address of p
*y == the value stored at p (another address)
**y == the value stored at b
By dereferencing y once we get the address stored at p. By dereferencing y again, we get the value stored at the address p points to. IOW, we get the value stored at b.
leroyjenkens said:
This problem is confusing. Here's what the first part says "Write a program that creates the structure shown in the figure below and reads data into a and b using the pointers x and y."

So I need to read data into a and b using the pointers x and y. What I did was read data into a and b using the pointers x and p, right? How do I go from using p to using y?
Part of what you did was OK, and part wasn't since it didn't use y to input a value to b. As a side note, it's not a good idea to input two or more variables at the same time using scanf. It's confusing for users and can lead to difficult to understand problems if you don't give it exactly the right input.

Code:
printf("Enter a value for a.\n");
scanf("%d", x);
printf("Enter a value for b.\n");
scanf("%d", ...);

You need to figure out what goes where the "..." is in the second call to scanf. It needs to be an expression that evaluates to the address of b. There are at least three ways to do this:
  1. &b
  2. p
  3. ?
Either of the first two would be fine, except they don't satisfy the requirement of using y. For this requirement you need an expression with y in it that evaluates to the address of b. Think about what I said before about the value that is stored in a pointer variable.
 
  • #13
You are correct gsal. However, so many people post homework programming problems here that we mentors sometimes don't bother moving them. Ya got to choose your battles.
 
  • #14
You're not adding x and y. That's not what *x + **y means.
Oh, I put in the code and typed in two numbers and it added the two numbers that I entered.
Here's a sketch of the drawing I did. It helps me keep things straight.
Yeah, that's what mine looks like, except it's upside down.
You need to figure out what goes where the "..." is in the second call to scanf. It needs to be an expression that evaluates to the address of b. There are at least three ways to do this:

&b
p
?

Either of the first two would be fine, except they don't satisfy the requirement of using y. For this requirement you need an expression with y in it that evaluates to the address of b. Think about what I said before about the value that is stored in a pointer variable.
I'm not sure if I did what you asked, but here's the code of what I changed.

I made **y = p
And then made return a*b;
Code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
   int c;
   int b;
   int a;
   int* x = &a;
   int* p = &b;
   int** y = p;
   int* q = &c;
   int** r = &q;
   int*** z = &r;
    printf("Enter a value for a: \n");
    scanf("%d", x);
    printf("Enter a value for b: \n");
    scanf("%d", y);    return a*b;
}
Were you wanting me to get the memory address of b using y?
Just a short twit:

According to this forum's guidelines requests for homework or self-study assistance should be post in the Homework & Coursework Questions area.

Regards

gsal
Oh, I'll remember that for next time. Thanks. I posted a few physics homework questions there, I don't know why I didn't think about putting this there too.
 
  • #15
These two lines aren't right.
Code:
scanf("%d", y);

return a*b;
In the call to scanf, a value that you enter is stored at the location that y is the address of, namely p. That's not what you want. This needs to be an expression that involves y.

What expression with y in it evaluates to the address of b? Look at the picture.

In your return statement, the basic problem requirements are not met.
Finally, it prints all three variables using the pointers x, y, and z.
So returning a * b doesn't meet the requirements. There should be one or more calls to printf inside main to print expressions involving x, y, and z.

Also, having main return the value means that you won't see the returned value, since main returns control to the operating system. main should return 0.
 
  • #16
Mark44 said:
These two lines aren't right.
Code:
scanf("%d", y);

return a*b;
In the call to scanf, a value that you enter is stored at the location that y is the address of, namely p. That's not what you want. This needs to be an expression that involves y.

What expression with y in it evaluates to the address of b? Look at the picture.

In your return statement, the basic problem requirements are not met.

So returning a * b doesn't meet the requirements. There should be one or more calls to printf inside main to print expressions involving x, y, and z.

Also, having main return the value means that you won't see the returned value, since main returns control to the operating system. main should return 0.

Is this correct?
Code:
    printf("Enter a value for a: \n");
    scanf("%d", x);
    printf("Enter a value for b: \n");
    scanf("%d", **y);    return 0;
}

If so, I had it like that before, but for some reason my program kept crashing every time I ran it, so I changed it, thinking the ** in the scanf statement was causing it. But now it's not crashing.

Edit: But now I just realized that **y is the value of b, not the memory address, right? I can't figure out how I would get the address of b without using p.
 
  • #17
No, **y is not the right expression in scanf, as you know.

As you also know, the value in p is the address you need. What other expression that involves y also contains this address? It's not a very complicated expression.
 
  • #18
Mark44 said:
No, **y is not the right expression in scanf, as you know.

As you also know, the value in p is the address you need. What other expression that involves y also contains this address? It's not a very complicated expression.

Is it &*y?

I did a printf("%d", &b)
And a printf("%d", &*y)
And I got back the same answer.
 
  • #19
You don't need the & operator - *y already is an address.
 
  • #20
I think I got it. Does this look right?

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

int main()
{
   int c;
   int b;
   int a;
   int* x = &a;
   int* p = &b;
   int** y = p;
   int* q = &c;
   int** r = &q;
   int*** z = &r;    printf("Enter a value for A: ");
    scanf("%d", x);
    printf("Enter a value for B: ");
    scanf("%d", *y);

    *z = *x * **y;
    printf("A * B = %d\n", *z);
    printf("C = %d\nA = %d\nB = %d", *z, *x, **y);

    return 0;
}
 
  • #21
The problem requirements are satisfied now. Does it give the right results?
 

FAQ: Help with simple pointer program

What is a pointer?

A pointer is a data type in programming that stores the memory address of another variable or data type. It allows for efficient manipulation and access of data in computer memory.

Why would I need to use pointers in a program?

Pointers are useful for tasks such as dynamic memory allocation, passing parameters to functions, and creating data structures. They also allow for more efficient memory usage, as they can be used to access and manipulate data without making unnecessary copies.

How do I declare and initialize a pointer in a program?

To declare a pointer in C, you use the asterisk symbol (*) before the variable name. For example, "int *ptr;". To initialize the pointer, you can assign it the address of another variable using the "address-of" operator (&), or use the "malloc" function to allocate memory dynamically.

What is the difference between a pointer and a reference?

A pointer is an actual object that holds the address of another variable, while a reference is an alias or nickname for an existing variable. Pointers can be reassigned to point to different objects, while references cannot be changed after initialization. Pointers also require dereferencing to access the value they point to, while references do not.

How do I avoid common errors and bugs when using pointers?

One common error when using pointers is dereferencing a null pointer, which can cause a program to crash. To avoid this, always check if a pointer is null before dereferencing it. Another common mistake is forgetting to allocate memory for a pointer before using it. It is also important to properly free allocated memory to avoid memory leaks.

Back
Top