Array Parameters and Pointers in C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

In C language, arrays are passed to functions as pointers by default. This means that when an array is passed as an argument to a function, the function receives a pointer to the first element of the array, and not a copy of the entire array.

Here is an example of passing an array by reference using a pointer:

Copy code

#include <stdio.h> void print_array(int* arr, int size) {    for (int i = 0; i < size; i++) {        printf("%d ", arr[i]);    }    printf("\n"); } int main() {    int a[5] = {1, 2, 3, 4, 5};    print_array(a, 5);    return 0; }

In this example, the print_array() function takes a pointer to an integer and an integer as arguments. The pointer is pointing to the first element of the array a, and the integer is the size of the array. The function uses the pointer to access the elements of the array and print them out.

It's also worth noting that when an array is passed as an argument to a function, its size is not passed along with it. If the size of the array is required inside the function, it must be passed as an additional argument.

Another way of passing an array to a function is by using the array name without any index, this will pass the pointer to the first element of the array to the function.

Copy code

#include <stdio.h> void print_array(int arr[], int size) {    for (int i = 0; i < size; i++) {        printf("%d ", arr[i]);    }    printf("\n"); } int main() {    int a[5] = {1, 2, 3, 4, 5};    print_array(a, 5);    return 0; }

This example is equivalent to the previous one, the only difference is the way the array is passed to the function, but the pointer to the first element of the array is passed to the function in both examples.

8. Pointers

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?