Taylor Hill
Taylor Hill

Reputation: 1124

Pointers for a beginner (with code)

I am doing my first ever homework assignment in C and I'm trying to grasp pointers. They make sense in theory, but in execution I'm a little fuzzy. I have this code, which is supposed to take an integer x, find its least significant byte, and replace y with that byte in the same location. GCC returns with:

"2.59.c:34:2: warning: passing argument 1 of ‘replace_with_lowest_byte_in_x’ makes pointer from integer without a cast [enabled by default]

2.59.c:15:6: note: expected ‘byte_pointer’ but argument is of type ‘int’"

And the same for argument 2. Would someone be so kind as to explain to me what is going on here?

#include <stdio.h>


typedef unsigned char *byte_pointer;


void show_bytes(byte_pointer start, int length) {
    int i;
    for (i=0; i < length; i++) {
        printf(" %.2x", start[i]);
    }
    printf("\n");
}

void replace_with_lowest_byte_in_x(byte_pointer x, byte_pointer y) {
    int length = sizeof(int);
    show_bytes(x, length);
    show_bytes(y, length);
    int i;
    int lowest;
    lowest = x[0];
    for (i=0; i < length; i++) {
        if (x[i] < x[lowest]) {
            lowest = i;
        }
    }
    y[lowest] = x[lowest];
    show_bytes(y, length);
}

int main(void) {


    replace_with_lowest_byte_in_x(12345,54321);

    return 0;
}

Upvotes: 0

Views: 99

Answers (2)

jfly
jfly

Reputation: 7990

The compiler is right, your replace_with_lowest_byte_in_x() expects two unsigned char *, but you pass two ints to it. Yes, the ints can be regarded as memory address, but it's dangerous, so there is a warning. &variable gives you the address of variable.

Upvotes: 2

Kninnug
Kninnug

Reputation: 8053

The function expects two pointers but you're passing integer(-constant)s. What you probably want is to put the numbers in their own variables and pass the addresses of those to the function: (in main):

int a = 12345, b = 54321;

replace_with_lowest_byte_in_x(&a, &b);

Note that you're still passing incompatible pointers.

Upvotes: 3

Related Questions