Pointers versus Arrays 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, pointers and arrays are closely related, but there are some key differences between them.

An array is a collection of elements of the same type, stored in contiguous memory locations. Each element of the array can be accessed by its index, starting from 0. Here's an example of an array:

Copy code

int a[5] = {1, 2, 3, 4, 5}; printf("%d\n", a[2]);  // prints 3

A pointer, on the other hand, is a variable that holds the memory address of another variable. Pointers can be used to dynamically allocate memory, traverse arrays, and perform other memory-related operations. Here's an example of a pointer:

Copy code

int x = 10; int* p = &x; printf("%d\n", *p);  // prints 10

One of the key differences between pointers and arrays is that a pointer is a variable and can be reassigned to point to different memory locations, while an array's name is a constant and cannot be reassigned.

Copy code

int x = 10; int y = 20; int* p = &x; p = &y; int a[5] = {1, 2, 3, 4, 5}; a = {6, 7, 8, 9, 10}; // this will cause a compile error

Another difference is that, when an array is passed to a function, it decays to a pointer to its first element, and the size of the array is not passed along with it. This means the function cannot determine the size of the array and any modification made to the elements of the array inside the function will change the original array too.

Copy code

void func(int* p, int size){    // Do something } int main(){    int a[5] = {1, 2, 3, 4, 5};    func(a, 5);    // Do something }

In general, arrays are useful when you know the size of the collection of data and you need to access elements by their index,

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?