arrays/array-limitations-2.c - Illustration af at et array ikke kopieres ved parameteroverførsel - compilerer og kører. | Lektion 9 - slide 4 : 30 Program 2 |
#include <stdio.h> #define TABLE_SIZE 11 void f (double p[TABLE_SIZE]){ int i; for(i = 0; i < TABLE_SIZE; i++) p[i] = p[i] * 2; // p is NOT a local copy of the actual parameter. // It is a pointer to the actual parameter array. } int main(void) { double a[TABLE_SIZE]; int i; for(i = 0; i < TABLE_SIZE; i++) a[i] = 2*i; for(i = 0; i < TABLE_SIZE; i++) /* 0 2 4 6 ... */ printf("Before calling f: a[%d] = %f\n", i, a[i]); printf("\n"); f(a); // The elements of a are not copied to f. // Instead a pointer to the first element in a is passed to f. // OK - but maybe not as intended. Compiles and runs. for(i = 0; i < TABLE_SIZE; i++) /* 0 4 8 12 ... */ printf("After calling f: a[%d] = %f\n", i, a[i]); return 0; }