We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37
Pointers and Arrays in C
int arr[4]={1, 2, 3, 4}
Arr has two purpose
• It is the name of the array • It acts as a pointer pointing towards the first element in the array.
arr is same as &arr[0]
• Use a pointer to an array, and then use that pointer to access the array elements. For example, Passing a single array element to a function • Declare and define an array of integers in main() function and pass one of the array element to a function, which will just print the value of the element. Passing 1-D Array to a Function in C unsigned int n = sizeof(arr)/sizeof(arr[0]); Returning an Array from a function We don't return an array from functions, rather we return a pointer holding the base address of the array to be returned. But we must, make sure that the array exists after the function ends i.e. the array is not local to the function. Array of 5 elements , each of which is a 1-D array of 2 elements Points to remember •Passing arrays to functions in C/C++ are passed by reference. Even though we do not create a reference variable, the compiler passes the pointer to the array, making the original array available for the called function’s use. Thus, if the function modifies the array, it will be reflected back to the original array.
•The equivalence between arrays and pointers to an
array is valid only and only for the function arguments.
•If an argument is a multidimensional array, its size must
be specified. However, the size of the first dimension is optional.