¿Qué es una estructura?
Una estructura es una palabra clave que crea un tipo de datos definido por el usuario en C/C++. Una estructura crea un tipo de datos que se puede usar para agrupar elementos de tipos posiblemente diferentes en un solo tipo.
C
struct address { char name[50]; char street[100]; char city[50]; char state[20]; int pin; };
C
// A variable declaration with structure declaration. struct Point { int x, y; } p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data types struct Point { int x, y; }; int main() { struct Point p1; // The variable p1 is declared like a normal variable }
C
struct Point { int x = 0; // COMPILER ERROR: cannot initialize members here int y = 0; // COMPILER ERROR: cannot initialize members here };
C
struct Point { int x, y; }; int main() { // A valid initialization. member x gets value 0 and y // gets value 1. The order of declaration is followed. struct Point p1 = {0, 1}; }
C
#include<stdio.h> struct Point { int x, y; }; int main() { struct Point p1 = {0, 1}; // Accessing members of point p1 p1.x = 20; printf ("x = %d, y = %d", p1.x, p1.y); return 0; }
C
#include<stdio.h> struct Point { int x, y, z; }; int main() { // Examples of initialization using designated initialization struct Point p1 = {.y = 0, .z = 1, .x = 2}; struct Point p2 = {.x = 20}; printf ("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z); printf ("x = %d", p2.x); return 0; }
C
#include<stdio.h> struct Point { int x, y; }; int main() { // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; printf("%d %d", arr[0].x, arr[0].y); return 0; }
C
#include<stdio.h> struct Point { int x, y; }; int main() { struct Point p1 = {1, 2}; // p2 is a pointer to structure p1 struct Point *p2 = &p1; // Accessing structure members using structure pointer printf("%d %d", p2->x, p2->y); return 0; }
C
struct number { float x; }; int main() { struct number n1,n2,n3; n1.x=4; n2.x=3; n3=n1+n2; return 0; } /*Output: prog.c: In function 'main': prog.c:10:7: error: invalid operands to binary + (have 'struct number' and 'struct number') n3=n1+n2; */
C
// Use of airthmatic operator in structure #include <stdio.h> struct number { float x; }; int main() { struct number n1,n2,n3; n1.x=4; n2.x=3; n3.x=(n1.x)+(n2.x); printf("\n%f",n3.x); return 0; }
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA