added weekly exercises of isp-ws25

This commit is contained in:
2026-04-13 19:02:19 +02:00
parent c51e836ed9
commit 00fdd31a18
28 changed files with 1835 additions and 0 deletions

View File

@@ -0,0 +1,70 @@
/*
In this task, you should get familiar with
malloc(), realloc() and free().
- user input: sequence of characters
- store in array of characters
- dynamically increase memory on heap for array
- temporary pointer for return value of realloc()
- add All characters to array until Q is entered
- check if mem-alloc OK after each malloc() / realloc()
- If mem-alloc NOK
- print: "Memory allocation failed\n"
- return 1
- free allocated memory at the end of main()
Examples:
awe s o m e !Q
Entered characters: a w e s o m e !
IS P ! :) Q
Entered characters: I S P ! : )
*/
#include <stdio.h>
#include <stdlib.h> // TODO: Include the required header file
int main(void)
{
int capacity = 2;
int count = 0;
char *characters = NULL;
characters = (char *)calloc(capacity, sizeof(char)); // TODO: Allocate memory (make use of the variable capacity)
if (characters == NULL)
{
printf("Memory allocation failed\n");
return 1;
} // TODO: Check if memory could be allocated
char value = 0;
while (scanf(" %c", &value) && value != 'Q')
{
if (count == capacity) // TODO: Check capacitiy and use realloc() to not run out of memory on the heap
{
capacity = capacity * count;
char *temp_chars = (char*)realloc(characters, sizeof(char) * capacity);
if (temp_chars == NULL)
{
printf("Memory allocation failed\n");
return 1;
}
characters = temp_chars;
} // TODO: Check if memory could be allocated
characters[count] = value;
count++;
// TODO: Add the entered value to the characters array
}
printf("Entered characters:");
for (int i = 0; i < count; i++)
{
printf(" %c", characters[i]);
}
printf("\n");
free(characters); // TODO: Free the allocated memory
return 0;
}