Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.2 KiB

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. int main(void) {
  4. int vector[5] = {1,2,3,4,5};
  5. int *pv;
  6. pv = vector;
  7. printf("length of vector: %zu\n", sizeof(vector)/sizeof(int));
  8. int matrix[2][3] = {{1,2,3},{4,5,6}};
  9. for (size_t index = 0; index < 2; index++) {
  10. printf("&matrix[%zu]: %p sizeof(matrix[%zu]): %zu\n",
  11. index, &matrix[index], index, sizeof(matrix[index]));
  12. }
  13. // pointer notation and arrays
  14. int value = 3;
  15. for(size_t index = 0; index < sizeof(vector)/sizeof(int); index++) {
  16. // all following operations are equivalent
  17. *pv++ *= value;
  18. //pv[index] *= value;
  19. //*(pv + index) *= value;
  20. //vector[index] *= value;
  21. }
  22. for(size_t index = 0; index < sizeof(vector)/sizeof(int); index++) {
  23. printf("vector[%zu]: %d\n", index, vector[index]);
  24. }
  25. // using malloc to create a one-dimensional array
  26. pv = (int*) malloc(5 * sizeof(int));
  27. for (size_t i = 0; i < 5; i++)
  28. {
  29. pv[i] = i + 1;
  30. }
  31. for (size_t i = 0; i < 5; ++i)
  32. {
  33. *(pv + i) = i + 1;
  34. }
  35. for(size_t index = 0; index < 5; index++) {
  36. printf("pv[%zu]: %d\n", index, pv[index]);
  37. }
  38. return 0;
  39. }