New in programming, problem with structures and functions

Hey, I'm new to programming (learning through cs50x in C), and when they mentioned structures, I decided to try to cheat and just write a quick program that would replace some values ​​in the structure with a function. I run up to a few error messages, the first of which is “incompatible pointer types that pass“ structure numbers * to a parameter of type “struct numbers *.” Another problem seems to arise in a function definition where the compiler says “incomplete type definition” struct number "" I was just hoping for some help because I'm at a dead end.

Here is the code (I know it roughly, 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", xa, xb, xc); 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; } 
+5
source share
4 answers

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

Ad break, it should be available to everyone who needs it. At the beginning, this will also eliminate the need for a preliminary declaration of the structure.

The same with swap() , placing 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) { . . . } 
+8
source

The problem is that the declaration of struct numbers is global, but the definition is local in main . To use structure members, the swap function must know which members the structure has and how it is possible. Do not see the definition that it does not know. Delete the declaration and place the definition in the global scope.

+6
source

The swap function cannot see the definition of struct numbers . Put it globally outside of main .

Extra tip. Use typedef with structures, this gives you flexibility in declaring:

 typedef struct typeNumbers { int a; int b; int c; } numbers; 

Please note that typeNumbers is optional. Declare it as:

 numbers x = {1, 2, 3}; 
+4
source

The problem was that the structure was mainly, I made some corrections in the code and commented on them.

 #include <stdio.h> //By defining the struct at the beginning you can avoid the forward declaration //and it make more sense to know what "numbers" is before continuing reading the code. struct numbers { int a; int b; int c; }; void swap(struct numbers* s) { //Small change to use only one temp variable... int temp2 = s -> b; s -> b = s -> a; s -> a = s -> c; s -> c = temp2; } int main(void) { struct numbers x = {1, 5 , 9}; swap(&x); printf("%i, %i, %i\n", xa, xb, xc); return 0; } 
+1
source

Source: https://habr.com/ru/post/1212086/


All Articles