Link to home
Start Free TrialLog in
Avatar of krampovpi
krampovpi

asked on

arrays and pointer incrementing

I know this is homework I just need help to get to the next step


Write a program that initializes and array-of-double and then copies the contents of the array into 2 other arrays.  (All three arrays should be declared in the main program.)  To make the 1st copy, use a function with array notation.  To make the 2nd copy use a function with pointer notation and pointer incrementing.  Have each function take as arguments the name of the target array and the number of elements to be copied.  That is the function calls would like thi, given the following declarations:

 double source[5] = {1.1,2.2,3.3,4.4,5.5};
 double target1[5];
 double target2[5];
 copy_arr(target1, orig, 5);  
 copy_ptr(source,target, 5);

Below is what I have so far.  I need help getting started with the pointer part


#include <stdio.h>

void copy_arr(double source[], double target1[],int i);
void copy_ptr(double source[], double target1[],5);
int main(void)
{
    double orig[5] = {1.1,2.2,3.3,4.4,5.5};
    double target1[5];
   
      copy_arr(target1, orig, 5);  
    return 0;
}

void copy_arr(double ar1[] , double ar2[], int n)
{
   
    int i;
    for (i = 0; i < n; i++)
      {ar1 = ar2;}
      
}
Avatar of ozo
ozo
Flag of United States of America image

{ar1[i] = ar2[i];}
ozo correctly pointed out that you need to copy individual elements of the array inside the loop. It is not possible to assign an entire array to another

Function with pointers would be very similar to the one using arrays ... In fact a 1 D array, when passed as an argument, is received as a pointer with in the called function

These C FAQs should clarify the concept
http://www.lysator.liu.se/c/c-faq/c-2.html

To implement copy function using pointers, you need two pointers to traverse source and destination arrays respectively. This traversal would be in a loop very similar to the one you have in copy_arr function. Within the loop, you can either increment the pointers and assign or add loop counter to initial pointer values and then assign.

Note that incrementing a pointer makes it point to the next member of its *type*. e.g. if double are 4 bytes long and double * p is pointing to memory location 1000, then p+1 would point to memory location 1004 and NOT to 1001.

Cheers!
sunnycoder
ASKER CERTIFIED SOLUTION
Avatar of Exceter
Exceter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> Since double is typically 4 bytes in length

I meant to say...

Since double is typically 8 bytes in length, depending on your compiler and hardware platform, 5 * sizeof(double) would probably return 40.