Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ОПК, семинар №4

Ilya
February 27, 2015

ОПК, семинар №4

Указатели, динамическая память, строки, структуры, файлы, аргументы командной строки

Ilya

February 27, 2015
Tweet

More Decks by Ilya

Other Decks in Education

Transcript

  1. Указатели, начало void increment(int x) { x++; printf("Increment: %d\n", x);

    } void main() { int newx = 5; increment(newx); printf("Result: %d\n", newx); } > Increment: 6 > Result: 5
  2. #define SIZE 3 void shuffle(double array[], unsigned size) { //...

    } void main() { unsigned i; double array[SIZE] = {1.0, 2.0, 3.0}; shuffle(array, SIZE); for(i = 0; i < SIZE; i++) { printf("%.0lf ", array[i]); } } > 3 1 2
  3. int newx; printf("%p", &newx); // 0x7fffc6c02cc4 printf("%p", &newy); // 0x7fffc6c02cc8

    printf("%p", array); // 0x7fffc6c02ccc // 0x7fffc6c02cd0 // 0x7fffc6c02cd4 int newy; int array[3];
  4. Указатель — переменная, в которой хранится адрес в памяти. Диапазон

    значений зависит от архитектуры процессора. Специальное значение — NULL.
  5. void main() { int x = 5; int *px; px

    = &x; // 0x7fff2a4defd4 printf("%d %d; %p\n", x, *px, px); (*px)++; printf("%d %d; %p\n", x, *px, px); } > 5 5; 0x7ffff8626ad4 > 6 6; 0x7ffff8626ad4 Работа с указателями
  6. int newx; printf("%p", &newx); // 0x7fffc6c02cc4 printf("%p", &newy); // 0x7fffc6c02cc8

    printf("%p", array); // 0x7fffc6c02ccc // 0x7fffc6c02cd0 // 0x7fffc6c02cd4 int newy; int array[3]; int *pointer = array;
  7. int newx; printf("%p", &newx); // 0x7fffc6c02cc4 printf("%p", &newy); // 0x7fffc6c02cc8

    printf("%p", array); // 0x7fffc6c02ccc // 0x7fffc6c02cd0 // 0x7fffc6c02cd4 int newy; int array[3]; int *pointer = array; pointer++;
  8. void main() { int x = 5; int *px; px

    = &x; // 0x7fff2a4defd4 printf("%d %d; %p\n", x, *px, px); (*px)++; printf("%d %d; %p\n", x, *px, px); *px++; printf("%d %d; %p\n", x, *px, px); } > 5 5; 0x7ffff8626ad4 > 6 6; 0x7ffff8626ad4 > 6 -127767848; 0x7ffff8626ad8 Подводный камень №1
  9. Подводный камень №2 void func() { int x = 5;

    // объявление указателя + присваивание int *px = &x; *px = &x; // не работает, тип *px - int px = &x; // присваивание }
  10. Коды возврата void make_fibonacci(int n, int output[]) { if (n

    < 0) // ? Как объяснить, что не так? }
  11. // Возвращает 1 в случае успеха, 0 иначе int make_fibonacci(int

    n, int output[]) { if (n < 0) { return 0; } // … return 1; } void main() { … if (make_fibonacci(n, output) != 0) { // Счастье, радость } }
  12. Указатели и коды возврата: веселее вместе size_t fread( void *buffer,

    size_t size, size_t count, FILE *stream ); fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count.
  13. Массивы и указатели int array[4]; array[0], *(array + 0) array[2],

    *(array + 2) int int int int int int int int int int int int
  14. Пустота и преобразование void main() { void *pointer; int x

    = 5; pointer = &x; int *px = (int *) pointer; printf("%d\n", *px); }
  15. Подводный камень №3 void main() { void *pointer; int x

    = 5; pointer = &x; float *px = (float *) pointer; printf("%d\n", *px); } > -1679649000
  16. Подводный камень №4 void main() { float f = 1.0;

    char c = 'a'; printf("%f\n", (char) f); } > 0.000000
  17. Динамическая память #include <malloc.h> void *malloc(size_t size); void free(void *memblock);

    void *realloc(void *memblock, size_t size); void *calloc(size_t num, size_t size); void *memset(void *dest, int c, size_t count);
  18. #include <malloc.h> #include <stdio.h> void main() { int *array =

    NULL; int i; unsigned size; if(scanf("%u", &size) == 0) { return; } array = (int *) malloc(size * sizeof(int)); if(array == NULL) { return; } for(i = 0; i < size; i++) { array[i] = i; } free(array); }
  19. array = (int *) calloc(size, sizeof(int)); for(i = 0; i

    < size; i++) { printf("%d ", array[i]); } < 4 > 0 0 0 0
  20. Файлы FILE *fopen( сonst char *filename, const char *mode); //

    mode = r, w+, ab size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream); int fclose(FILE *stream);
  21. #include <malloc.h> #include <string.h> #include <stdio.h> void main() { FILE*

    file; size_t written; file = fopen("test.txt", "w"); if (file == NULL) { return; } char msg[] = "Hello, World!"; written = fwrite(msg, sizeof(char), strlen(msg), file); if (written == 0) { printf("Nothing written :(\n"); } fclose(file); }
  22. int msg[] = {1, 2, 3, 4, 5}; written =

    fwrite(msg, sizeof(int), 5, file); > cat test.txt > ^A^@^@^@^B^@^@^@^C^@^@^@^D^@^@^@^E^@^@^@
  23. #define SIZE 5 void main() { FILE* file; size_t read;

    int i; file = fopen("test.txt", "r"); if (file == NULL) { ... } int* message = (int*) malloc(SIZE * sizeof(int)); if (message == NULL) { ... fclose(file); } read = fread(message, sizeof(int), SIZE, file); if (read < SIZE) { printf("Read less than expected: %d\n", read); } for(i = 0; i < read; i++) { printf("%d ", message[i]); } free(message); fclose(file); }
  24. int count, total = 0; char buffer[100]; FILE *stream; fopen_s(&stream,

    "crt_feof.txt", "r"); if(stream == NULL) exit(1); while(!feof(stream)) { count = fread(buffer, sizeof(char), 100, stream); if(ferror(stream)) { perror("Read error"); break; } total += count; } printf("Number of bytes read = %d\n", total); fclose(stream );
  25. Структуры char* names[]; double balances[]; double limits[]; … void withdraw(const

    char* name, double* balance, double limit, double price) {…} for(i = 0; i < size; i++) { withdraw(names[i], &balances[i], limits[i], 30); }
  26. Структуры struct Account { char* user_name; double money_left; double daily_limit;

    }; void withdraw(Account* account, double price) {…} Account accounts[]; for(i = 0; i < size; i++) { withdraw(&account[i], 30); }
  27. Аргументы #include <stdio.h> void main(int argc, char* argv[]) { int

    i; for(i = 0; i < argc; i++) { printf("Arg %d is %s\n", i, argv[i]); } } > main.exe C is kinda hard Arg 0 is main.exe Arg 1 is C Arg 2 is is Arg 3 is kinda Arg 4 is hard
  28. #include <stdio.h> #include <math.h> void main(int argc, char* argv[]) {

    int i, number, squared; if (argc != 2) { printf("Use: %s x_to_square\n", argv[0]); return; } number = atoi(argv[1]); squared = (int) pow(number, 2); printf("%d squared is %d\n", number, squared); }