简体   繁体   中英

Using pointers in C programming?

Right now I'm working on a program in C that takes 3 parameters; the address of a "first" integer, address of the "second" integer and the address in which to store the maximum of the two integers. So far I have the following basic code:

void max(int* x, int* y, int* z)
{

    if (x > y) {
        z = x;
    }
    else if (y > x){
        z = y;
    }
}

int main()
{
    int x = 6;
    int y = 4;
    int z;
    max(&x, &y, &z);
    printf("max of %d and %d = %d\n", x, y, z);

    x = 12;
    y = 17;
    max(&x, &y, &x);
    printf("x = %d, y = %d\n", x, y);
}

When executed it outputs the following:

max of 6 and 4 = 32767
x = 12, y = 17

HOWEVER! I want it to output this instead:

max of 6 and 4 = 6
x = 17, y = 17

I'm not sure where I'm going wrong in my max function. Z should not be so huge and in the second print statement x should equal y . Any help is greatly appreciated, thanks!

As you probably already know, a pointer is a variable which contains the address in memory of another variable.

To access that memory we use The Unary operator & which gives us the address of a variable .

But accessing that memory is not all what a Pointer can do, we can with that pointer modify the value of that variable where the pointer points to. For that we need to supply * to that pointer like this *ptr .

Let's take a look at the following program:

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

int main(void){

    int a = 5;
    int b = 10;

    printf("A = %d\nB = %d\n\n\n",a,b);

    int *pa = &a;
    int *pb = &b;

    *pa = 50;
    *pb = 100;

    printf("A = %d\nB = %d\n*PA = %d\n*PB = %d\n",a,b,*pa,*pb);

    return 0;
}

The output will be:

 A = 5 B = 10 
A = 50
B = 100
*PA = 50
*PB = 100

As you can see A and B got new values. I hope you understand that.

when you pass things by pointer, if you want to get to the values, you need to do

(*x > *y)

Which gets the value pointed at by the pointer. (x and y are pointers, so they are going to contain memory addresses of the where the values are stored)

Needs to be:

if (*x > *y) {
    *z = *x;
}
else if (*y > *x){
    *z = *y;
}

You are comparing pointer addresses. You should de-reference the pointers for comparisons and assignments.

void max(int* x, int* y, int* z)
{

    if (*x > *y) {
        *z = *x;
    }
    else if (*y > *x){
        *z = *y;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM