diiferent between * and & in c
The '*' symbol in C is used to declare a pointer variable and to dereference a pointer to access the value it points to. On the other hand, the '&' symbol is used to obtain the address of a variable.
- Declaration of a Pointer:
int *ptr;
Here, '*' is used to declare a pointer to an integer.
- Dereferencing a Pointer:
int x = 10;
int *ptr = &x;
int value = *ptr;
Here, '*' is used to dereference the pointer 'ptr' to obtain the value stored at the address it points to.
- Function Parameters:
void myFunction(int *ptr) {
// Function code
}
In function parameters, '*' is used to declare a pointer parameter, allowing the function to receive the address of a variable.
- Address of Operator:
int x = 20;
int *ptr = &x;
The '&' symbol is used to get the address of the variable 'x' and assign it to the pointer 'ptr'.
- Pointers and Arrays:
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr;
Here, '*' is used to declare a pointer 'ptr' that points to the first element of the array 'arr'.
- Dynamic Memory Allocation:
int dynamicPtr = (int )malloc(sizeof(int));
The '*' symbol is used to declare a pointer that will hold the address of a dynamically allocated memory block.
In summary: - '*' is used to declare a pointer and to dereference a pointer. - '&' is used to obtain the address of a variable.