Elysia Tools

Explora herramientas, ejemplos, explicaciones visuales y guías temáticas en un solo espacio claro.

Categorías populares

Temas

Idioma
ZHDERUPTENFRES

Elysia Tools

Navegación

Lenguajes de programación

Ejemplos de C

Ejemplos esenciales de programación C y fundamentos de programación de sistemas

Ejemplos

Entradas de esta colección

CódigocSimple

Hola Mundo en C

Programa Hola Mundo básico y ejemplos de sintaxis fundamental

Dificultad

2/10

Tiempo estimado

15 min

Etiquetas

c, programming, beginner

Requisitos previos

Basic programming concepts

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

// 1. Basic Hello World
int main() {
    printf("Hello, World!\n");
    return 0;
}

// 2. Hello World with function
void sayHello() {
    printf("Hello, World!\n");
}

// 3. Hello World with function parameters
void greet(const char* name) {
    printf("Hello, %s!\n", name);
}

// 4. Hello World with variables
int main_variables() {
    const char* message = "Hello, World!";
    printf("%s\n", message);

    char name[50];
    printf("Enter your name: ");
    scanf("%49s", name);
    printf("Hello, %s!\n", name);

    return 0;
}

// 5. Hello World with command line arguments
int main_args(int argc, char* argv[]) {
    if (argc > 1) {
        printf("Hello, %s!\n", argv[1]);
    } else {
        printf("Hello, World!\n");
    }
    return 0;
}

// 6. Hello World multiple times
int main_multiple() {
    for (int i = 0; i < 5; i++) {
        printf("Hello, World! %d\n", i + 1);
    }
    return 0;
}

// 7. Hello World with array
int main_array() {
    const char* greetings[] = {"Hello", "Bonjour", "Hola", "Ciao"};
    int count = sizeof(greetings) / sizeof(greetings[0]);

    for (int i = 0; i < count; i++) {
        printf("%s, World!\n", greetings[i]);
    }

    return 0;
}

// 8. Basic data types
int main_types() {
    // Integer types
    int integer = 42;
    short short_num = 10;
    long long_num = 1000000;
    unsigned int unsigned_num = 50;

    // Floating point types
    float float_num = 3.14f;
    double double_num = 2.71828;

    // Character type
    char character = 'A';

    // Boolean (since C99)
    bool flag = true;

    printf("Integer: %d, size: %zu bytes\n", integer, sizeof(integer));
    printf("Float: %.2f, size: %zu bytes\n", float_num, sizeof(float_num));
    printf("Double: %.5f, size: %zu bytes\n", double_num, sizeof(double));
    printf("Character: %c, size: %zu bytes\n", character, sizeof(character));
    printf("Boolean: %d, size: %zu bytes\n", flag, sizeof(bool));

    return 0;
}

// 9. Control flow examples
int main_control_flow() {
    int age = 18;

    // If-else statement
    if (age >= 18) {
        printf("You are an adult\n");
    } else {
        printf("You are a minor\n");
    }

    // Switch statement
    int day = 3;
    switch (day) {
        case 1: printf("Monday\n"); break;
        case 2: printf("Tuesday\n"); break;
        case 3: printf("Wednesday\n"); break;
        default: printf("Other day\n"); break;
    }

    // Loop examples
    for (int i = 0; i < 3; i++) {
        printf("For loop iteration: %d\n", i);
    }

    int j = 0;
    while (j < 3) {
        printf("While loop iteration: %d\n", j);
        j++;
    }

    return 0;
}

// 10. Basic arithmetic operations
int main_arithmetic() {
    int a = 10, b = 3;

    printf("Addition: %d + %d = %d\n", a, b, a + b);
    printf("Subtraction: %d - %d = %d\n", a, b, a - b);
    printf("Multiplication: %d * %d = %d\n", a, b, a * b);
    printf("Division: %d / %d = %d\n", a, b, a / b);
    printf("Modulus: %d %% %d = %d\n", a, b, a % b);

    // Floating point division
    float fa = 10.0f, fb = 3.0f;
    printf("Float division: %.2f / %.2f = %.2f\n", fa, fb, fa / fb);

    return 0;
}
CódigocIntermedio

Punteros y Gestión de Memoria C

Ejemplos completos de punteros C, asignación de memoria y gestión

Dificultad

7/10

Tiempo estimado

30 min

Etiquetas

c, pointers, memory, systems programming

Requisitos previos

Basic C syntax, Understanding of memory concepts

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 1. Basic pointer concepts
int basic_pointers() {
    int num = 42;
    int* ptr = &num;  // ptr stores the address of num

    printf("Value of num: %d\n", num);
    printf("Address of num: %p\n", (void*)&num);
    printf("Value stored in ptr: %p\n", (void*)ptr);
    printf("Value pointed to by ptr: %d\n", *ptr);
    printf("Address of ptr: %p\n", (void*)&ptr);

    // Modifying value through pointer
    *ptr = 100;
    printf("New value of num: %d\n", num);

    return 0;
}

// 2. Pointer arithmetic
int pointer_arithmetic() {
    int arr[] = {10, 20, 30, 40, 50};
    int* ptr = arr;  // Points to first element

    printf("Array elements using pointer arithmetic:\n");
    for (int i = 0; i < 5; i++) {
        printf("arr[%d] = %d (address: %p)\n", i, *(ptr + i), (void*)(ptr + i));
    }

    // Pointer increments
    printf("\nPointer increments:\n");
    int* current = arr;
    for (int i = 0; i < 5; i++) {
        printf("Element %d: %d\n", i, *current);
        current++;  // Move to next element
    }

    return 0;
}

// 3. Dynamic memory allocation
int dynamic_memory() {
    // Allocating memory for an integer
    int* dynamic_int = (int*)malloc(sizeof(int));
    if (dynamic_int == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    *dynamic_int = 42;
    printf("Dynamically allocated integer: %d\n", *dynamic_int);
    free(dynamic_int);
    printf("Memory freed\n");

    // Allocating memory for an array
    int size = 5;
    int* dynamic_array = (int*)malloc(size * sizeof(int));
    if (dynamic_array == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    // Initialize array
    for (int i = 0; i < size; i++) {
        dynamic_array[i] = i * 10;
    }

    printf("\nDynamic array elements:\n");
    for (int i = 0; i < size; i++) {
        printf("dynamic_array[%d] = %d\n", i, dynamic_array[i]);
    }

    // Resize array
    int new_size = 10;
    int* resized_array = (int*)realloc(dynamic_array, new_size * sizeof(int));
    if (resized_array == NULL) {
        printf("Reallocation failed!\n");
        free(dynamic_array);
        return 1;
    }

    // Initialize new elements
    for (int i = size; i < new_size; i++) {
        resized_array[i] = i * 10;
    }

    printf("\nResized array elements:\n");
    for (int i = 0; i < new_size; i++) {
        printf("resized_array[%d] = %d\n", i, resized_array[i]);
    }

    free(resized_array);
    return 0;
}

// 4. Pointers and strings
int pointer_strings() {
    // String literal (read-only)
    const char* str_literal = "Hello, World!";
    printf("String literal: %s\n", str_literal);

    // Dynamic string allocation
    char* dynamic_str = (char*)malloc(50 * sizeof(char));
    if (dynamic_str == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    strcpy(dynamic_str, "Dynamic string");
    printf("Dynamic string: %s\n", dynamic_str);

    // Modifying dynamic string
    strcat(dynamic_str, " with more text");
    printf("Modified string: %s\n", dynamic_str);

    // String operations with pointers
    printf("\nString character by character:\n");
    for (char* p = dynamic_str; *p != '\0'; p++) {
        printf("'%c' (%d) ", *p, (int)*p);
    }
    printf("\n");

    free(dynamic_str);
    return 0;
}

// 5. Function pointers
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
int subtract(int a, int b) { return a - b; }
int divide(int a, int b) { return b != 0 ? a / b : 0; }

int function_pointers() {
    // Array of function pointers
    int (*operations[])(int, int) = {add, multiply, subtract};
    const char* operation_names[] = {"Addition", "Multiplication", "Subtraction"};

    int a = 10, b = 5;

    for (int i = 0; i < 3; i++) {
        int result = operations[i](a, b);
        printf("%s: %d %s %d = %d\n", operation_names[i], a,
               i == 0 ? "+" : i == 1 ? "*" : "-", b, result);
    }

    int result = divide(20, 4);
    printf("Division result: %d\n", result);

    return 0;
}

// 6. Double pointers
int double_pointers() {
    int num = 42;
    int* ptr = &num;
    int** double_ptr = &ptr;

    printf("Value: %d\n", num);
    printf("Via pointer: %d\n", *ptr);
    printf("Via double pointer: %d\n", **double_ptr);

    // Modifying via double pointer
    **double_ptr = 100;
    printf("New value: %d\n", num);

    return 0;
}

// 7. Memory leak simulation (don't do this in production!)
int memory_leak_example() {
    printf("Memory allocation examples:\n");

    // Correct allocation and deallocation
    int* good_ptr = (int*)malloc(sizeof(int));
    if (good_ptr != NULL) {
        *good_ptr = 42;
        printf("Good pointer value: %d\n", *good_ptr);
        free(good_ptr);
        printf("Good pointer freed correctly\n");
    }

    // Memory leak (intentionally not freeing for demonstration)
    int* leak_ptr = (int*)malloc(sizeof(int));
    if (leak_ptr != NULL) {
        *leak_ptr = 100;
        printf("Leak pointer value: %d\n", *leak_ptr);
        // NOT freeing leak_ptr - this creates a memory leak
        printf("Warning: leak_ptr not freed (memory leak)\n");
    }

    // Double free (demonstrates what NOT to do)
    int* double_free_ptr = (int*)malloc(sizeof(int));
    if (double_free_ptr != NULL) {
        *double_free_ptr = 200;
        free(double_free_ptr);
        printf("Double free pointer freed once\n");
        // free(double_free_ptr); // This would cause undefined behavior
        printf("Second free avoided (would cause crash)\n");
    }

    return 0;
}

// 8. Structures with pointers
typedef struct Student {
    char* name;
    int age;
    float* grades;
    int num_grades;
} Student;

int structures_with_pointers() {
    // Allocate student structure
    Student* student = (Student*)malloc(sizeof(Student));
    if (student == NULL) return 1;

    // Allocate and set name
    student->name = (char*)malloc(50 * sizeof(char));
    if (student->name == NULL) {
        free(student);
        return 1;
    }
    strcpy(student->name, "John Doe");

    student->age = 20;
    student->num_grades = 3;

    // Allocate grades array
    student->grades = (float*)malloc(student->num_grades * sizeof(float));
    if (student->grades == NULL) {
        free(student->name);
        free(student);
        return 1;
    }

    student->grades[0] = 85.5f;
    student->grades[1] = 92.0f;
    student->grades[2] = 78.5f;

    printf("Student: %s, Age: %d\n", student->name, student->age);
    printf("Grades: ");
    for (int i = 0; i < student->num_grades; i++) {
        printf("%.1f ", student->grades[i]);
    }
    printf("\n");

    // Free all allocated memory
    free(student->grades);
    free(student->name);
    free(student);

    return 0;
}

int main() {
    printf("=== C Pointers and Memory Management Examples ===\n\n");

    printf("1. Basic Pointers:\n");
    basic_pointers();
    printf("\n");

    printf("2. Pointer Arithmetic:\n");
    pointer_arithmetic();
    printf("\n");

    printf("3. Dynamic Memory Allocation:\n");
    dynamic_memory();
    printf("\n");

    printf("4. Pointers and Strings:\n");
    pointer_strings();
    printf("\n");

    printf("5. Function Pointers:\n");
    function_pointers();
    printf("\n");

    printf("6. Double Pointers:\n");
    double_pointers();
    printf("\n");

    printf("7. Memory Management Examples:\n");
    memory_leak_example();
    printf("\n");

    printf("8. Structures with Pointers:\n");
    structures_with_pointers();
    printf("\n");

    return 0;
}
CódigocComplejo

E/S de Archivos y Programación de Sistemas C

Operaciones de archivo, llamadas al sistema y programación de bajo nivel

Dificultad

8/10

Tiempo estimado

35 min

Etiquetas

c, file operations, systems programming, unix

Requisitos previos

C pointers, Memory management, Operating system concepts

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <time.h>

// 1. Basic file I/O with stdio
int basic_file_io() {
    FILE* file;
    const char* filename = "example.txt";

    // Write to file
    file = fopen(filename, "w");
    if (file == NULL) {
        perror("Error opening file for writing");
        return 1;
    }

    fprintf(file, "Hello, C File I/O!\n");
    fprintf(file, "This is line 2\n");
    fprintf(file, "Number: %d\n", 42);
    fprintf(file, "Float: %.2f\n", 3.14);

    fclose(file);
    printf("Data written to %s\n", filename);

    // Read from file
    file = fopen(filename, "r");
    if (file == NULL) {
        perror("Error opening file for reading");
        return 1;
    }

    printf("\nReading file content:\n");
    char line[256];
    while (fgets(line, sizeof(line), file) != NULL) {
        printf("%s", line);
    }

    fclose(file);
    return 0;
}

// 2. Binary file operations
int binary_file_operations() {
    const char* filename = "data.bin";
    int numbers[] = {10, 20, 30, 40, 50};
    int count = sizeof(numbers) / sizeof(numbers[0]);

    // Write binary data
    FILE* file = fopen(filename, "wb");
    if (file == NULL) {
        perror("Error opening binary file for writing");
        return 1;
    }

    fwrite(numbers, sizeof(int), count, file);
    fclose(file);
    printf("Binary data written to %s\n", filename);

    // Read binary data
    int read_numbers[10];
    file = fopen(filename, "rb");
    if (file == NULL) {
        perror("Error opening binary file for reading");
        return 1;
    }

    size_t items_read = fread(read_numbers, sizeof(int), 10, file);
    fclose(file);

    printf("Read %zu items:\n", items_read);
    for (size_t i = 0; i < items_read; i++) {
        printf("read_numbers[%zu] = %d\n", i, read_numbers[i]);
    }

    return 0;
}

// 3. Low-level file operations (Unix-style)
int low_level_file_ops() {
    const char* filename = "lowlevel.txt";
    const char* content = "Low-level file operations in C\n";

    // Write using write() system call
    int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1) {
        perror("Error opening file with open()");
        return 1;
    }

    ssize_t bytes_written = write(fd, content, strlen(content));
    if (bytes_written == -1) {
        perror("Error writing to file");
        close(fd);
        return 1;
    }

    close(fd);
    printf("Wrote %zd bytes using low-level I/O\n", bytes_written);

    // Read using read() system call
    fd = open(filename, O_RDONLY);
    if (fd == -1) {
        perror("Error opening file for reading");
        return 1;
    }

    char buffer[256];
    ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
    if (bytes_read == -1) {
        perror("Error reading from file");
        close(fd);
        return 1;
    }

    buffer[bytes_read] = '\0'; // Null terminate
    printf("Read %zd bytes: %s\n", bytes_read, buffer);

    close(fd);
    return 0;
}

// 4. File information and status
int file_status_operations() {
    const char* filename = "example.txt";
    struct stat file_stat;

    if (stat(filename, &file_stat) == -1) {
        perror("Error getting file status");
        return 1;
    }

    printf("File status for %s:\n", filename);
    printf("  Size: %ld bytes\n", file_stat.st_size);
    printf("  Permissions: ");
    printf((file_stat.st_mode & S_IRUSR) ? "r" : "-");
    printf((file_stat.st_mode & S_IWUSR) ? "w" : "-");
    printf((file_stat.st_mode & S_IXUSR) ? "x" : "-");
    printf((file_stat.st_mode & S_IRGRP) ? "r" : "-");
    printf((file_stat.st_mode & S_IWGRP) ? "w" : "-");
    printf((file_stat.st_mode & S_IXGRP) ? "x" : "-");
    printf((file_stat.st_mode & S_IROTH) ? "r" : "-");
    printf((file_stat.st_mode & S_IWOTH) ? "w" : "-");
    printf((file_stat.st_mode & S_IXOTH) ? "x" : "-");
    printf("\n");

    printf("  Last modified: %s", ctime(&file_stat.st_mtime));
    printf("  Is directory: %s\n", S_ISDIR(file_stat.st_mode) ? "Yes" : "No");
    printf("  Is regular file: %s\n", S_ISREG(file_stat.st_mode) ? "Yes" : "No");

    return 0;
}

// 5. Directory operations (Unix-style)
int directory_operations() {
    const char* dirname = "test_dir";

    // Create directory
    if (mkdir(dirname, 0755) == -1) {
        if (errno != EEXIST) {
            perror("Error creating directory");
            return 1;
        }
        printf("Directory already exists\n");
    } else {
        printf("Directory created successfully\n");
    }

    // Change directory permissions
    if (chmod(dirname, 0777) == -1) {
        perror("Error changing directory permissions");
        return 1;
    }
    printf("Directory permissions changed\n");

    // Note: Directory listing would require opendir/readdir which are platform-specific
    printf("Directory operations completed\n");

    return 0;
}

// 6. Process information
int process_info() {
    printf("Process Information:\n");
    printf("  Process ID: %d\n", getpid());
    printf("  Parent Process ID: %d\n", getppid());
    printf("  User ID: %d\n", getuid());
    printf("  Group ID: %d\n", getgid());

    return 0;
}

// 7. Environment variables
int environment_variables() {
    printf("Environment Variables:\n");

    // Get specific environment variable
    char* path = getenv("PATH");
    if (path != NULL) {
        printf("  PATH (first 100 chars): %.100s...\n", path);
    }

    char* home = getenv("HOME");
    if (home != NULL) {
        printf("  HOME: %s\n", home);
    }

    // Set environment variable
    if (setenv("MY_VAR", "Hello from C", 1) == 0) {
        char* my_var = getenv("MY_VAR");
        printf("  MY_VAR: %s\n", my_var ? my_var : "Not found");
    }

    return 0;
}

// 8. Error handling demonstration
int error_handling_examples() {
    printf("Error Handling Examples:\n");

    // Try to open non-existent file
    FILE* file = fopen("nonexistent_file.txt", "r");
    if (file == NULL) {
        printf("  fopen error: %s (errno: %d)\n", strerror(errno), errno);
    } else {
        fclose(file);
    }

    // Try to allocate huge amount of memory
    size_t huge_size = SIZE_MAX;
    void* ptr = malloc(huge_size);
    if (ptr == NULL) {
        printf("  malloc error: %s (errno: %d)\n", strerror(errno), errno);
    } else {
        free(ptr);
    }

    return 0;
}

// 9. Time and date operations
int time_operations() {
    time_t current_time;
    struct tm* time_info;
    char time_string[80];

    time(&current_time);
    time_info = localtime(&current_time);

    strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info);
    printf("Current time: %s\n", time_string);

    printf("Year: %d\n", time_info->tm_year + 1900);
    printf("Month: %d\n", time_info->tm_mon + 1);
    printf("Day: %d\n", time_info->tm_mday);
    printf("Hour: %d\n", time_info->tm_hour);
    printf("Minute: %d\n", time_info->tm_min);
    printf("Second: %d\n", time_info->tm_sec);

    return 0;
}

// 10. Command execution
int command_execution() {
    printf("Command Execution Examples:\n");

    // Execute a simple command
    int result = system("echo 'Hello from system() call'");
    printf("system() call returned: %d\n", result);

    // Note: For more control, you'd use fork() and exec() family
    printf("Command execution completed\n");

    return 0;
}

int main() {
    printf("=== C File I/O and System Programming Examples ===\n\n");

    printf("1. Basic File I/O:\n");
    basic_file_io();
    printf("\n");

    printf("2. Binary File Operations:\n");
    binary_file_operations();
    printf("\n");

    printf("3. Low-level File Operations:\n");
    low_level_file_ops();
    printf("\n");

    printf("4. File Status Operations:\n");
    file_status_operations();
    printf("\n");

    printf("5. Directory Operations:\n");
    directory_operations();
    printf("\n");

    printf("6. Process Information:\n");
    process_info();
    printf("\n");

    printf("7. Environment Variables:\n");
    environment_variables();
    printf("\n");

    printf("8. Error Handling Examples:\n");
    error_handling_examples();
    printf("\n");

    printf("9. Time Operations:\n");
    time_operations();
    printf("\n");

    printf("10. Command Execution:\n");
    command_execution();
    printf("\n");

    return 0;
}

Herramientas

Herramientas que suelen usarse con este ejemplo

Relacionado

Colecciones de ejemplos relacionadas

Relacionado

Temas relacionados

Tema

Revisión e integración de un componente de sorteos autoalojado

Revisa la configuración, las respuestas de ejemplo, la legibilidad y el diseño adaptable antes de entregar los archivos y las pruebas de integración del sorteo.

Tema

Modelos farmacocineticos docentes y revision de resultados

Explora formulas farmacocineticas, supuestos de modelo y coherencia de resultados para docencia o QA, sin dar dosis ni consejo clinico.

Tema

Herramientas de cifrado clásico y moderno

Practica cifrados seguros para educación o CTF comparando transformaciones clásicas reversibles con cifrado moderno y sus límites de seguridad.

Tema

Revisión de una lección Markdown interactiva y entrega sin conexión

Revisa contenido y configuración, ensaya el HTML exportado sin conexión y separa archivos del público de fuentes privadas.

Inicio
Herramientas3212
Ejemplos593
Visualizaciones471
Visores de archivos103
Temas239
Etiquetas333
Imágenes, audio y video657

Herramientas de procesamiento, conversión y optimización de imágenes, audio y video

Matemáticas, fechas y finanzas647

Calculadoras, herramientas numéricas, lógica de fechas, estadística y finanzas

Diseño y color298

Herramientas de color, maquetación, gráficos, estilo visual y apoyo al diseño

Texto y redacción209

Herramientas de redacción, limpieza, formato, extracción y análisis de texto

Desarrollo y Web193

Utilidades para desarrolladores, red, depuración web y automatización

Conversión y codificación175

Herramientas de conversión de formatos, archivos, unidades, archivos comprimidos y codificación

Lanzamiento de un cuestionario de captación y entrega de contactos
Textos conmemorativos: revisión familiar y entrega para impresión
Hábitos privados: copia, restauración y revisión antes de compartir
De artículo a borradores de X y LinkedIn: revisión factual y entrega
Revisión de una lección Markdown interactiva y entrega sin conexión

© 2026 Elysia Tools. Todos los derechos reservados.

DocumentaciónPreciosAcerca deTérminos de servicioPolítica de privacidadCookiesContacto

Development

Validador de Nombres de Variable - Verificador de Convenciones de Nombres Multi-Lenguaje

Validar nombres de variables contra convenciones y estándares de nombres de múltiples lenguajes de programación

AI Tools

Detector de Idioma AI

Detecta el idioma de fragmentos de texto y devuelve códigos de idioma usando IA

Media

Creador de bucles para idiomas

Convierte frases de voz en una pista de práctica repetible con pausas configurables.

AI Tools

Traductor de Títulos Multiidioma IA Ilimitado

Herramienta profesional de traducción de títulos multiidioma con IA para películas, series, anime, juegos y más, con salida en formato JSON

Lenguajes de programación

Ejemplos de Ensamblador

Ejemplos esenciales de programación en lenguaje ensamblador para programación de bajo nivel

Lenguajes de programación

Ejemplos Zig

Ejemplos de lenguaje de programación Zig - programación de sistemas simple y eficiente con seguridad de memoria