Browse Source

adding example to using malloc to create a one-dimensional array

master
T. Meissner 11 years ago
parent
commit
3494ac292e
1 changed files with 19 additions and 2 deletions
  1. +19
    -2
      c_pointers/chapter_4.c

+ 19
- 2
c_pointers/chapter_4.c View File

@ -5,7 +5,9 @@
int main(void) {
int vector[5] = {1,2,3,4,5};
int *pv = vector;
int *pv;
pv = vector;
printf("length of vector: %zu\n", sizeof(vector)/sizeof(int));
@ -16,18 +18,33 @@ int main(void) {
index, &matrix[index], index, sizeof(matrix[index]));
}
// pointer notation and arrays
int value = 3;
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++) {
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++)
{
pv[i] = i + 1;
}
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]);
}
return 0;
}

Loading…
Cancel
Save