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.

88 lines
2.2 KiB

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. void displayArray(int arr[], size_t size);
  4. void displayArrayPtr(int *arr, size_t size);
  5. void displayArray(int arr[], size_t size) {
  6. for (size_t i = 0; i < size; i++) {
  7. // both variants are possible
  8. printf("%d\n", arr[i]);
  9. //printf("%d\n", *(arr + i));
  10. }
  11. }
  12. void displayArrayPtr(int *arr, size_t size) {
  13. for (size_t i = 0; i < size; i++) {
  14. // both variants are possible
  15. printf("%d\n", *(arr + i));
  16. //printf("%d\n", arr[i]);
  17. }
  18. }
  19. int main(void) {
  20. int vector[5] = {1,2,3,4,5};
  21. int *pv;
  22. pv = vector;
  23. printf("length of vector: %zu\n", sizeof(vector)/sizeof(int));
  24. int matrix[2][3] = {{1,2,3},{4,5,6}};
  25. for (size_t index = 0; index < 2; index++) {
  26. printf("&matrix[%zu]: %p sizeof(matrix[%zu]): %zu\n",
  27. index, &matrix[index], index, sizeof(matrix[index]));
  28. }
  29. // pointer notation and arrays
  30. int value = 3;
  31. for (size_t index = 0; index < sizeof(vector)/sizeof(int); index++) {
  32. // all following operations are equivalent
  33. *pv++ *= value;
  34. //pv[index] *= value;
  35. //*(pv + index) *= value;
  36. //vector[index] *= value;
  37. }
  38. for (size_t index = 0; index < sizeof(vector)/sizeof(int); index++) {
  39. printf("vector[%zu]: %d\n", index, vector[index]);
  40. }
  41. // using malloc to create a one-dimensional array
  42. pv = (int*) malloc(5 * sizeof(int));
  43. for (size_t i = 0; i < 5; i++) {
  44. pv[i] = i + 1;
  45. }
  46. for (size_t i = 0; i < 5; ++i) {
  47. *(pv + i) = i + 1;
  48. }
  49. for(size_t index = 0; index < 5; index++) {
  50. printf("pv[%zu]: %d\n", index, pv[index]);
  51. }
  52. // passing array to function using array notation
  53. displayArray(vector, sizeof(vector)/sizeof(int));
  54. // passing array to function using pointer notation
  55. displayArrayPtr(vector, sizeof(vector)/sizeof(int));
  56. // using one-dimensional array of pointers
  57. {
  58. int *arr[5];
  59. for (size_t i = 0; i < 5; i++) {
  60. // both variants are equivalent
  61. arr[i] = (int*) malloc(sizeof(int));
  62. *arr[i] = i;
  63. //*(arr + i) = (int*) malloc(sizeof(int));
  64. //**(arr + i) = i;
  65. }
  66. }
  67. return 0;
  68. }