Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to programming, issue with structures and functions

Tags:

c

Hey I'm new to programming (learning through cs50x in C) and when they mentioned structures I decided to try to fool around and just write a quick program that would swap some values in a structure using a function. I'm running until several error messages, the first of which is "incompatible pointer types passing 'struct numbers*' to parameter of type 'struct numbers*'. Another issue seems to come up in the function definition where the compiler says "incomplete definition of type 'struct number'" I was just hoping for some help cause I'm stumped.

Heres the code (I know its rough but I'm learning lol)

#include <stdio.h>
struct numbers;
void swap(struct numbers* s);

int main(void)
{
    struct numbers
    {
        int a;
        int b;
        int c;
    };
    struct numbers x = {1, 5 , 9};
    swap(&x);
    printf("%i, %i, %i\n", x.a, x.b, x.c);
    return 0;
}

void swap(struct numbers* s)
{
    int temp = s -> a;
    int temp2 = s -> b;
    s -> a = s -> c;
    s -> b = temp;
    s -> c = temp2;
}
like image 345
ashissl Avatar asked Jan 28 '15 08:01

ashissl


1 Answers

You're expecting the code in swap() to be able to access the fields of struct numbers, but the full declaration of that type is inside main(), so it's not visible.

Break out the declaration, it must be visible to all who need it. Putting it first will also remove the need to pre-declare the structure.

The same with swap() itself, putting it before main() will remove the need to have a prototype for it in the same file.

It should be:

struct numbers
{
 .
 .
 .
}

static void swap(struct numbers *s)
{
 .
 .
 .
}

int main(void)
{
 .
 .
 .
}
like image 90
unwind Avatar answered Nov 09 '22 15:11

unwind