6

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;     
}
1
  • @Everyone, Thank you guys for clearing my doubts.. Commented Jul 25, 2011 at 10:33

5 Answers 5

5

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;     
}
Sign up to request clarification or add additional context in comments.

4 Comments

does prefix or postfix in for loop will make any difference.
No pre-incrementing vs post-incrementing shouldn't make any difference in this case. I'm used to writing the former since the latter involves making a temporary copy of the object being incremented. This can be significant in case of C++ and custom classes that define operator++. But here it should be identical in either case.
Last time I did C was several months ago. If I have a dynamically allocated integer array, I'd have to store the size I passed to malloc in order to make it through the loop without wandering past the edge of that block of memory, right?
@Ungeheuer Yes, there's no (portable) way to retrieve the size of allocated array if you only have the pointer returned by malloc.
3

You have several options:

  • You could pass the size of your array into the function.
  • You could have a special "sentinel" value (e.g. -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.

7 Comments

something like void(int *ptr, int size){ for int i =0; i<size; ptr++) printf("%d", *(ptr+i));
just for curiousity , is there is any way that pointers can determine size of array in for loop may be using pointers to pointers etc. This is only my wild guess
@samprat: Yes, something like this (but don't forget to also increment i).
@axis, yeah i almost forget to increment i.. Thanks
and *(ptr+i) is equivalent to ptr[i] so it's losing the point of iterating using pointer.
|
1

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:

  • A special termination marker used for the last element. For strings this is NULL. In your example it could be -1, if that value will never occur in the real data.
  • Passing a length parameter to 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));

Comments

0

The function needs to know the size of the array. There are two common approaches:

  1. 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;     
    }
    
  2. 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;     
    }
    

1 Comment

Your sample solution not only solved my main problem but also helped me to clear few more doubts. THANKS
0

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;     
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.