Browse Source

more examples up to chapter 'using one-dimensional array of pointers'

master
T. Meissner 11 years ago
parent
commit
ed5721dcb0
1 changed files with 45 additions and 6 deletions
  1. +45
    -6
      c_pointers/chapter_4.c

+ 45
- 6
c_pointers/chapter_4.c View File

@ -2,6 +2,28 @@
#include <stdio.h>
void displayArray(int arr[], size_t size);
void displayArrayPtr(int *arr, size_t size);
void displayArray(int arr[], size_t size) {
for (size_t i = 0; i < size; i++) {
// both variants are possible
printf("%d\n", arr[i]);
//printf("%d\n", *(arr + i));
}
}
void displayArrayPtr(int *arr, size_t size) {
for (size_t i = 0; i < size; i++) {
// both variants are possible
printf("%d\n", *(arr + i));
//printf("%d\n", arr[i]);
}
}
int main(void) {
int vector[5] = {1,2,3,4,5};
@ -20,31 +42,48 @@ int main(void) {
// pointer notation and arrays
int value = 3;
for(size_t index = 0; index < sizeof(vector)/sizeof(int); index++) {
for (size_t index = 0; index < sizeof(vector)/sizeof(int); index++) {
// all following operations are equivalent
*pv++ *= value;
//pv[index] *= value;
//*(pv + index) *= value;
//vector[index] *= value;
}
for(size_t index = 0; index < sizeof(vector)/sizeof(int); index++) {
for (size_t index = 0; index < sizeof(vector)/sizeof(int); index++) {
printf("vector[%zu]: %d\n", index, vector[index]);
}
// using malloc to create a one-dimensional array
pv = (int*) malloc(5 * sizeof(int));
for (size_t i = 0; i < 5; i++)
{
for (size_t i = 0; i < 5; i++) {
pv[i] = i + 1;
}
for (size_t i = 0; i < 5; ++i)
{
for (size_t i = 0; i < 5; ++i) {
*(pv + i) = i + 1;
}
for(size_t index = 0; index < 5; index++) {
printf("pv[%zu]: %d\n", index, pv[index]);
}
// passing array to function using array notation
displayArray(vector, sizeof(vector)/sizeof(int));
// passing array to function using pointer notation
displayArrayPtr(vector, sizeof(vector)/sizeof(int));
// using one-dimensional array of pointers
{
int *arr[5];
for (size_t i = 0; i < 5; i++) {
// both variants are equivalent
arr[i] = (int*) malloc(sizeof(int));
*arr[i] = i;
//*(arr + i) = (int*) malloc(sizeof(int));
//**(arr + i) = i;
}
}
return 0;
}

Loading…
Cancel
Save