0

I want to pass a array to function and I want to change it within the function without changing the original array using c. Can I do it?

This is what I have so far:

#include <stdio.h>

void display(int age[]) {
    age[0]=3;
    age[1]=4;
}
int main() {
    int ageArray[] = { 2,3 };
    display(ageArray);//Passing array element ageArray[2] only.
    printf("%d", ageArray[0]);
    return 0;
} 
6
  • Make a copy, and pass the copy. Or have the called function make a copy. I suppose if the dimensions are fixed, you could embed it in a struct and pass the struct by value. Commented Nov 6, 2017 at 9:23
  • You need to duplicate the array. Commented Nov 6, 2017 at 9:23
  • #include <stdio.h> void display(int age[]) { age[0]=3; age[1]=4; } int main() { int ageArray[] = { 2,3 }; display(ageArray); //Passing array element ageArray[2] only. printf("%d",ageArray[0]); return 0; } my code is like this how can i make a copy of this array Commented Nov 6, 2017 at 9:24
  • Create a copy of the array passed within your function. All changes made to this copy of the array will be local to the function. Commented Nov 6, 2017 at 9:24
  • 1
    Please don't change or extend your question with a comment. Use the "EDIT" function of the question and mark the edition that you can see what has been changed. Commented Nov 6, 2017 at 9:28

1 Answer 1

3

C doesn't have to concept of passing arrays to a function. There is always a pointer passed to the function independent of the function signature:

void function(int *Array);
void function(int Array[]);

You must make a copy of the array if you want to avoid modification of the original array. For that purpose you must pass the size of the Array:

void function(int *Array, size_t Size);

Now you can create the copy.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much

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.