Alexandros Voliotis
Alexandros Voliotis

Reputation: 318

warning: assignment makes pointer from integer without a cast [-Wint-conversion]

I want to Prompt the user to enter 3 numbers. Then, swap the first number with the second one, the second number with the third and the third with the first by calling a function called "swap".

Functions in C cannot return more than one value so I decided to create a structure with pointers that I will later use in my function. Then, I created three-pointers that will store the address of each one of the numbers so I can dereference to these numbers in my function (as shown below)

Number.pa = *ppb;
Number.pb = *ppc;
Number.pc = *ppa;

Here's my code:

#include <stdio.h>

void swap(); // a = b, b = c, c = a

struct Numbers {

    int *pa, *pb, *pc;

} ;

int main(void) {

    struct Numbers Number; // Structure to hold the values of the three variables.

    int a, b, c;
    int *ppa, *ppb, *ppc;                                              
    printf("\n Please enter three integer numbers: ");  
    scanf("%d%d%d", &a, &b, &c);
    ppa = &a; ppb = &b; ppc = &c;                                         
    swap(a, b, c, Number, *ppa, *ppb, *ppc);
    printf("\n %d \t %d \t %d \n", Number.pa, Number.pb, Number.pc);
}

void swap(int a, int b, int c, struct Numbers Number, int *ppa, int *ppb, int *ppc) { 

    Number.pa = *ppb;
    Number.pb = *ppc;
    Number.pc = *ppa;  

   } ;

Upvotes: 0

Views: 2590

Answers (1)

WhozCraig
WhozCraig

Reputation: 66244

Most of the arguments to your swap function are either pointless or the work of sheer guessing (or both). The assignment effectively wants you to "rotate" values from a through c. So do that, and only that.

#include <stdio.h>

void swap(int *pa, int *pb, int *pc);

int main() 
{
    int a, b, c;

    printf("\n Please enter three integer numbers: ");  
    if (scanf("%d %d %d", &a, &b, &c) == 3)
    {
        swap(&a, &b, &c);
        printf("%d %d %d \n", a, b, c);
    }
    return 0;
}

void swap(int *pa, int *pb, int *pc)
{ 
    int tmp = *pa;
    *pa = *pb;
    *pb = *pc;
    *pc = tmp;
}

Stop reading more into an assignment than is there. If it sounds simple, it probably is. The warning was due to passing the value of dereferenced pointers to int (so int values) to a function expecting int pointers; not int values. As you can see, you don't need to do any of that (and didn't in the first place).

Upvotes: 2

Related Questions