Reputation: 2214
I am stuck about how to use pointers to display array. I can easily do this with array using for loop but I am interested in knowing how to use via pointers and I am stuck how to calculate starting and ending point of an array.
Below is the sample program
void printArray(int *ptr);
{
//for statement to print values using array
for( ptr!=NULL; ptr++) // i know this doesn't work
printf("%d", *ptr);
}
int main()
{
int array[6] = {2,4,6,8,10};
printArray(array);
return 0;
}
Upvotes: 6
Views: 58944
Reputation: 109169
The checking for NULL trick only works for NULL terminated strings. For a numeric array you'll have to pass in the size too.
void printArray(int *ptr, size_t length);
{
//for statement to print values using array
size_t i = 0;
for( ; i < length; ++i )
printf("%d", ptr[i]);
}
void printString(const char *ptr);
{
//for statement to print values using array
for( ; *ptr!='\0'; ++ptr)
printf("%c", *ptr);
}
int main()
{
int array[6] = {2,4,6,8,10};
const char* str = "Hello World!";
printArray(array, 6);
printString(str);
return 0;
}
Upvotes: 5
Reputation: 3515
Here is the answer buddy (Non-tested)...
void printArray(int arr[]);
{
int *ptr;
for(ptr = &arr[0]; ptr <= &arr[5]; ptr++)
{
if(ptr != null)
printf("%d", *ptr);
ptr++; // incrementing pointer twice, as there are ‘int' values in array which
//are of size 2 bytes, so we need to increment it twice..
}
}
int main()
{
int array[6] = {2,4,6,8,10};
printArray(array);
return 0;
}
Upvotes: 0
Reputation: 11922
The function needs to know the size of the array. There are two common approaches:
Pass the actual size to the function, e.g.
void printArray(int *ptr, size_t size)
{
int *const end = ptr + size;
while( ptr < end ) {
printf("%d", *ptr++);
}
}
int main()
{
int array[6] = {2,4,6,8,10};
printArray(array, sizeof(array) / sizeof(array[0]) );
return 0;
}
Explicitly provide a sentinel 0 (or other appropriate) element for the array:
void printArray(int *ptr);
{
//for statment to print values using array
for( *ptr != 0; ptr++) // i know this doesn't work
printf("%d", *ptr);
}
int main()
{
int array[6] = {2,4,6,8,10, NULL};
printArray(array);
return 0;
}
Upvotes: 0
Reputation: 500495
You have several options:
-1
) as the last element of your array; if you do this, you must ensure that this value cannot appear as part of the array proper.Upvotes: 3
Reputation: 69270
When an array is passed as a parameter to a function, it is decayed into a pointer to the first element of the array, loosing the information about the length of the array. To handle the array in the receiving function (printArray
) requires a way to know the length of the array. This can be done in two ways:
NULL
. In your example it could be -1
, if that value will never occur in the real data.printArray
.This would give the following for
statements:
//Marker value.
for(;*ptr != -1; ++ptr)
printf("%d", *ptr);
//Length parameter
for(int i = 0; i < length; ++i)
printf("%d", *(ptr+i));
Upvotes: 1