- Plagiatscheck!
- sizeof
- Strukturen
- File-IO
- Command-line Arguments
- Dynamischer Speicher
- Übungsbeispiel
int charsize = sizeof(char);
int ptrsize = sizeof(int*);
int size = sizeof("Hallo");
int x[20]; int len = sizeof(x) / sizeof(x[0]);
int x[20]; int* y = x; int len = sizeof(y) / sizeof(y[0]);
char* hallo = "Hallo"; int size = sizeof(hallo);
#include <stdio.h> struct _Person_ { char* name; int age; }; int main() { struct _Person_ petra; petra.name = "Petra"; petra.age = 17; return 0; }
typedef
:
[...] struct _Person_ { char* name; int age; }; typedef struct _Person_ Person; [...] Person petra; petra.name = "Petra"; petra.age = 17; [...]
struct _Person_ { char* name; int age; struct _Person_* father; struct _Person_* mother; };
struct
in Datei speichernstruct
s können in Binärdateien gespeichert werden[...] struct _Phone_ { int country_code; int number; }__attribute__((packed)); [...] struct _Phone_ number; number.number = 1234567; number.country_code = 43; FILE* file = fopen("phone_numbers", "wb"); // wb = write binary fwrite(&number, sizeof(struct _Phone_), 1, file); fclose(file);
struct
in Datei gespeichert werden soll
|
|
struct
aus Datei lesenstruct
s können aus Binärdateien geladen werden[...] struct _Phone_ { int country_code; int number; }__attribute__((packed)); [...] struct _Phone_ number; FILE* file = fopen("phone_numbers", "rb"); // rb = read binary fread(&number, sizeof(struct _Phone_), 1, file); fclose(file);
int
in einer Datei aus?78 56 34 12
fread
:
int length; fread(&length, sizeof(int), 1, file);
// buffer is the char array containing the file int length = *((int*)buffer);
memcpy
in einen Integer kopieren:
// buffer is the char array containing the file int length; memcpy(&length, buffer, sizeof(int));
long size; fseek(file, 0, SEEK_END); size = ftell(file); fseek(file, 0, SEEK_SET);
int main (int argc, char *argv[]) { int count; printf ("This program was called with \"%s\".\n",argv[0]); if (argc > 1) { for (count = 1; count < argc; count++) { printf("argv[%d] = %s\n", count, argv[count]); } } else { printf("The command had no other arguments.\n"); } return 0; }
size
an (in Bytes angegeben)
1int main()
{
2 int* mem = (int*)malloc(sizeof(int) * 2);
3 if(mem == NULL) return 0;
4 *mem = 1;
5 *(mem + 1) = 2;
6 mem[0] = 3;
7 mem[1] = 4;
8 free(mem);
return 0;
}
|
Heap:
Heap:
Heap:
Heap:
Heap:
Heap:
Heap:
Heap:
|
NULL
initialisierenfree
auf NULL
setzenmalloc
/realloc
auf NULL
überprüfenrealloc
Hilfspointer verwenden:
char* text = (char*)malloc(8 * sizeof(char)); char* new_text = (char*)realloc(text, 16 * sizeof(char)); if(new_text != NULL) { text = new_text; } else { free(text); printf("Out of memory!\n"); }
Abgabeschluss: