Function that copies an array and modifies its elements

copy array javascript
why does changing an array in javascript affect copies of the array?
javascript copy array of objects without reference
assign array to variable javascript
javascript array pass by value
vue copy array
typescript copy array
es6 copy array spread

I was asked to define a function array_ncopy() that takes in three arguments:

  • int *ptr represents a pointer to an array of integers

  • int array represents the size of the array

  • int n represents an integer

and that copies the elements of the array pointed at by *ptr to another list. However all the elements with the index greater than NUMBER will be copied as 0

This is my code:
#include <stdio.h>
#include <stdlib.h>
#define NUMBER 12
#define MAX  100
#define SIZE  8

void array_print(int *ptr, int array) {
    for (int i = 0; i < array; i++){
        printf("Value of array[%d] is %d",i, ptr[i]);
        printf("\n");
    }
}

int* array_create(int array) {
    int *t = malloc(array * sizeof(int));
    for (int i = 0; i < array; i++) {
        t[i] = rand() % MAX;
    }

    return t;
}

int* array_ncopy(int *ptr, int array, int n) {
    for (int i=0; i < n; i++){
        if (i >= n) {
            ptr[i] = 0;
        }
        ptr[i] = ptr[i];
    }
    return ptr;
}

int main() {
  int *t = array_create(SIZE);
  int *ptr = array_ncopy(t, SIZE, NUMBER);
  array_print(ptr, NUMBER);
  free(t);
  free(ptr);
  return 0;
}

Take for example this array:

{23, 7, 4, 32, 55, 2, 78, 26}
I should get this as a result:

For NUMBER = 4:

Value of array[0] is 83
Value of array[1] is 86
Value of array[2] is 77
Value of array[3] is 15

For NUMBER = 12:

Value of array[0] is 83
Value of array[1] is 86
Value of array[2] is 77
Value of array[3] is 15
Value of array[4] is 93
Value of array[5] is 35
Value of array[6] is 86
Value of array[7] is 92
Value of array[8] is 0
Value of array[9] is 0
Value of array[10] is 0
Value of array[11] is 0
Instead I get this output:

FOR NUMBER = 12

Value of array[0] is 83
Value of array[1] is 86
Value of array[2] is 77
Value of array[3] is 15
Value of array[4] is 93
Value of array[5] is 35
Value of array[6] is 86
Value of array[7] is 92
Value of array[8] is 0
Value of array[9] is 0
Value of array[10] is 4113
Value of array[11] is 0

Could someone correct my code so that it outputs the right thing.

According to the specification, the copy function should be:

int* array_ncopy(int *ptr, int array, int number)
{
    int *new_array= malloc(array*sizeof(int));
    for (int i=0; i < array; i++){
        if (i >= number) {
            new_array[i] = 0;
        }
        else new_array[i] = ptr[i];
    }
    return new_array;
}

This copies the element to a new array (as specified). The array size is the same size as the old array (as implicitly specified). All elements from the old array whose index is <= number are copied and elements greater than this are set to zero. If number >= array then no elements are set to zero (as implicitly specified).

Functions on copies of an array modify the original array (No , It seems that using functions such as .push, .pop, .shift, .unshift and .splice on a copy of an array will modify the original as well and I don't understand why. lines 28 and 29 to return the 2 element array to its original order. The third additionally ensures the array parameters have exactly 4 elements (so suddenly you can't (easily) pass say an array of 10 elements and have it copy over only the first 4). The fourth accepts any sizes of array, but if used from different calling code on different sized arrays it may create multiple copies of the myFunction code

This is what compiler warnings are for:

++ clang -Wall -Wextra -std=c11 -pedantic-errors prg.c
prg.c:23:32: warning: unused parameter 'array' [-Wunused-parameter]
int* array_ncopy(int *ptr, int array, int n) {
                               ^
1 warning generated.

You are not using the variable array at all. Do:

for (int i=0; i < array; i++){

A Student's Guide to Python for Physical Modeling, You could convert it to an array with np.array(rest). You can overwrite the array and modify its elements without making any copies. If you really do intend for a function to modify the elements of an array, you can still avoid side effects. Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 64-bit integer. Copy(Array, Array, Int32) Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer.

Another approach:

int *array_ncopy(int *ptr, unsigned int size, unsigned int number)
{
    // create a zero-filled array the same size
    int *newArray = calloc( size, sizeof( *newArray ) );

    // error checking - ALWAYS do error checking!
    if ( !newArray )
    {
        return( NULL );
    }

    // copy the first "number" elements to the new array
    // making sure to limit the max amount copied
    number = MIN( number, size );
    memcpy( newArray, ptr, number * sizeof( *newArray ) );
    return( newArray );
}

Also, using signed int to represent the number of elements in an array is nonsensical and could lead to some strange bugs.

The Zend PHP Certification Practice Test Book: Practice Questions , The 12 13 14 15 - $array array will contain only one element, since true If you needed a function to modify the array's contents, you'd have no choice but to pass not actually create a copy of a variable until it is modified, passing an array by  In this video tutorial for beginners you will learn how to copy an array and its elements in java programming in detail with example. You will learn how to use a loop to copy the elements

Since there are a couple of really confusing and sometimes wrong things, i will try to go through them one by one to make it a bit clearer.

#define NUMBER 12 
#define MAX  100
#define SIZE 8

here NUMBER > SIZE; Which means your array will never reach the upper_bound.

    int* array_ncopy(int *ptr, int array, int n)
 {
    for (int i = 0; i < n; i++) 
        if (i >= n) {
            ptr[i] = 0;
        }
        ptr[i] = ptr[i];
    }
    return ptr;
}

for(int i = 0; i < n; i++) - here you are looping till n(upper bound) and not the array size is reached.

This ptr[i] = ptr[i]; doesnt copy the value to another array, but simply assigns the value to the same array again. Instead, you have to create an array int *cpy = (int*)malloc(length * sizeof(int)); and then assign the values to it like so:

    int* array_ncopy(int *ptr, int length, int upperBound) // ptr = first array
    {    
int *cpy = (int*)malloc(length * sizeof(int)); // create copy array
        for (int i = 0; i < length; i++)
        {
            if (i >= upperBound) 
                cpy[i] = 0; 
            else
            cpy[i] = ptr[i]; // copy to array if i < upperBound
        }
        return cpy;
    }

Aside from that:

Your naming scheme is pretty unclear in pretty much all function declarations(the names are fine, but your variable names could be more descriptive). It is kinda hard to really know at first glance what int* array_ncopy(int *ptr, int array, int n) array(since its an int and not a ptr) and or n might mean here. So i would suggest to change it to array_ncopy(int *ptr, int length, int upperBound)

Below you can find your program in a more idiomatic way(and working)

#include <stdio.h>
    #include <stdlib.h>
    #define UPPER_BOUND 8
    #define MAX  100
    #define SIZE  12

void array_print(int *ptr, int length) {
    for (int i = 0; i < length; i++) {
        printf("Value of array[%d] is %d", i, ptr[i]);
        printf("\n");
    }
}

int* array_create(int length) {
    int *t = (int*)malloc(length * sizeof(int));
    for (int i = 0; i < length; i++) {
        t[i] = rand() % MAX;
    }

    return t;
}

    int* array_ncopy(int *ptr, int length, int upperBound)
    {    
int *cpy = (int*)malloc(length * sizeof(int));
        for (int i = 0; i < length; i++)
        {
            if (i >= upperBound)
                cpy[i] = 0;
            else
            cpy[i] = ptr[i];
        }
        return cpy;
    }

    int main()
 {
    int *t = array_create(SIZE);
    int *cpy = array_ncopy(t, SIZE, UPPER_BOUND);
    array_print(cpy, SIZE);
    free(t);
    free(cpy);
    return 0;
}

Javascript Array: Copy Value or Reference, How to copy or pass a JavaScript array and modify it while leaving the original If you apply the slice or ( concat ) method to an array whose elements are  It seems that array is a local variable inside both caller function and callee function. Its address is copied and passed from test_change to change: Inside change: +---+---+--+ array -----> -> | 1 | 2 | 3| /-> +---+---+--+ test --------. Let's verify above observation with another function change2:

Try this one

int* array_ncopy(int *ptr, int array, int n) {
    for (int i=0; i < array; i++){
        if (i >= n) {
            ptr[i] = 0;
        }
        ptr[i] = ptr[i];
    }
    return ptr;
}

Good luck

Array methods, The arr.splice(start) method is a swiss army knife for arrays. It It returns a new array copying to it all items from index start to end (not including end ). array, but the returned value is usually ignored, as arr itself is modified. To prevent modification of array values passed to a function: 1. The array parameter can be preceded by the const qualifier. 2. A copy of the array must be made inside the function. 3. The array must be passed by reference. 4. The array must be declared static in the function.

Java array pass by reference, You can pass a variable by reference to a function so the function can modify the Unlike a traditional array that store values like string, integer, Boolean, etc an Java creates a copy of references and pass it to method, but they still point to  when compiler encounters a function parameter for a single-subscripted array of the form int a;', it converts parameter to int * a when calling a function with argument that should be modified, the ________________ of those arguments are passed.

Array.Copy Method (System), Copies a range of elements in one Array to another Array and performs type casting and GetUpperBound(0) - 1, 2 ); // Displays the values of the modified arrays. A value type is considered connected to an interface only if it implements that  Write a method that takes as its parameter an array a of integers and modifies the given array so that it contains a running sum of its original values. For example, if the array originally had the values [3 2 4 7], after running your method that array would instead contain [3 5 9 16], and if you ran it another time on the same array, you'd

Array.prototype.copyWithin(), The copyWithin() method shallow copies part of an array to another location in the same array and returns it without modifying its length. copy to index 1 all elements from index 3 to the end. 8. console.log(array1. Derive a function in Python called add, that takes an array and modifies it by adding 1 to all the elements. Create another function Python called add_V2, which takes an array and returns a new array containing the values of the given array provided as a parameter incremented by 1, without modifying it.

Comments
  • for (int i=0; i < n; i++) -> for (int i = 0; i < array; i++). BTW, ptr[i] = ptr[i]; is a no-op.
  • ptr[i] = ptr[i] doesn't really copy anything. And what is the pointer returned by array_ncopy? I suggest you do some rubber duck debugging on your code.
  • how do I make it copy the elements of the pointed list? The pointer returned by array_ncopy should be the new modified list?
  • You probably want a malloc somewhere in your array_ncopy function
  • The creaste function must create an array of MAX(SIZE,NUMBER). Currently it does not.
  • Your code makes complete sense, however I get the same output? Why does this print 4113 instead of 0 Value of array[10] is 4113
  • @MisterTusk - since your test case passes a value of number that exceeds array, none of the elements returned will differ from those passed. In other words, new_array[i] = 0 will never be executed for any element. Pass those two arguments in opposite order if you want a visible change.
  • ptr[i] = ptr[i]; is nonsense and overwrites ptr[i]= 0;.