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,
Comments: 0