iam feelin little vague while passing array to functions and passing function to a function...could u plzz explain...

Dani AI

Generated

As asked about passing arrays and passing functions: a short, practical clarification that ties together 's and 's points.

In C an array expression used as a function argument "decays" to a pointer to its first element; that pointer is passed by value. The callee sees and can modify the original buffer (no automatic element copying). A common pitfall is using sizeof inside the callee to get element count — sizeof yields the size of the pointer there, not the original array.

Example (safe pattern):

void fill(int *a, size_t n) {
    for (size_t i = 0; i < n; ++i) a[i] = (int)i;
}

int main(void) {
    int arr[10];
    fill(arr, 10);   // pass pointer + explicit length
}

Passing a function (callback) is done with function pointers. Function names decay to pointers as well; either f or &f is acceptable. Use a typedef to simplify signatures:

typedef void (*callback_t)(int);

void apply(int *a, size_t n, callback_t cb) {
    for (size_t i = 0; i < n; ++i) cb(a[i]);
}

void print_val(int v) { printf("%d\n", v); }
apply(arr, 10, print_val);

Additional tips:

  • Use const for read-only buffers (const int *a) to document intent.
  • To pass an entire array by value, wrap it in a struct (struct copies are by value).
  • Beware of returning pointers to local (stack) arrays — allocate or return by struct instead.
  • For variable-length arrays (C99), signatures like void f(size_t n, int a[n]) are allowed, but still pass a pointer + size.

Further reference: C arrays and .

Recommended Answers

All 3 Replies

specifically what would you want to know?

arrays are transferred by value to a function, and functions are called by other functions just as integers or floats would be...

arrays are transferred by value to a function,

Not really -- only the pointer is passed by value, all data is passed by reference, that is, the data is at the same address location in both the calling and called functions. You can not pass array data by value in c language which would imply that the data is duplicated when passed to the calling function.

sorry... my bad...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.