0

** I would like to copy the pointer array to a new pointer so the original array won't change**

/* The main contains a pointer (p) to an array */
int main()
{
...
...
...

p = (int*)malloc(length*sizeof(int));

z = (int*)copyArray(p, length);
    
    printArray(z, length);
    
    return 0;
} 

/* end of main */

CopyArray func /* copy the array, return a new pointer to a new array with same size and values */

 int copyArray(int *p, int length)
    {
            int *z = (int*)malloc(length*sizeof(int));
            
            for(length--; length>=0; length--)
            {
                z[length] = p[length];
                
            }
            
            return *z;
    }

printArray func /* The function receives a pointer to an array and it's length. it will print the values that the array contains by the order */

void printArray(int *p, int length)
    {
        int i = 0;
        for(; i<length; i++)
        {
            printf("\n %d \n", p[i]);
                
        }
    }
Eliran_B
  • 3
  • 2
  • 1
    `int copyArray(...)` and `z = (int*)copyArray(...)` is definitely going to give you a problem. Don't use casting to silence the compiler, it usually knows these things better than you. – Some programmer dude Nov 29 '20 at 10:46
  • Also, you [should not cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Nov 29 '20 at 12:00

1 Answers1

0

Reason for not working : return *z; here you are returning only one element *(z+0) = z[0] not the whole array. Check the code below:

#include <stdio.h>
#include <stdlib.h>

int *copyArray(int *p, int length)  // Change return type to `int *`
{
    int *z = malloc(length * sizeof(int)); // No need to cast output of malloc

    for (length--; length >= 0; length--)
    {
        z[length] = p[length];
    }

    return z;  // return the pointer.
}

void printArray(int *p, int length)
{
    int i = 0;
    for (; i < length; i++)
    {
        printf("\n %d \n", p[i]);
    }
}

int main()
{
    int *p;
    int *z;
    int length =5;

    p = malloc(length*sizeof(int)); // No need of casting

    for(int i=0 ;i<length; i++)
    {
        p[i] = i;  // assigning some values
    }

    z = copyArray(p, length);  // Donot cast return of the function
    printArray(z, length);

    return 0;
}

The output is :

 0 

 1 

 2 

 3 

 4 
Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26