Passing Structs to the Functions
main.c
#include <stdio.h> // structure definition typedef struct { char name[50]; } Person; // function to display information about a person void printPerson(Person p) { printf("Name: %s\n", p.name); } int main() { // creating a structure and initializing its values Person person1 = {"John"}; // call a function to display information about a person printPerson(person1); return 0; }
main.c
#include <stdio.h> // structure definition Typedef struct { char symbol; }Example; // function for changing the values of structure fields via a pointer void changePoint(Example* ptr, int newSymbol) { // check for NULL pointer if (ptr != NULL) { ptr->symbol = newSymbol; } } int main() { // create the Example structure and a pointer Example ptr1 = {'H'}; Example* ptr = &ptr1; printf("Old symbol: %c | %p\n", ptr1.symbol, &ptr1); // use function to change the field of structures changePoint(ptr, 'y'); printf("New symbol: %c | %p\n", ptr1.symbol, &ptr1); return 0; }
main.c
#include <stdio.h> #include <stdlib.h> // structure definition typedef struct { int value; }Example; // function creates a structure with the given field Example* CreateStruct(int setVal) { Example* ptr = (Example*)malloc(sizeof(Example)); // check for successful memory allocation if (ptr != NULL) { ptr->value = setVal; return ptr; } } int main() { // use function to create structure Example* ptrToStruct = CreateStruct(23); printf("Value inside struct: %d", ptrToStruct->value); free(ptrToStruct); // free memory return 0; }
Compito
Swipe to start coding
Soluzione
Tutto è chiaro?
Grazie per i tuoi commenti!