Thread: Array coping into another array?or function returning array

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    20

    Array coping into another array?or function returning array

    My problem looks like that i have class wich have some array and i need to pass it somwhere alse. How to do it? I've tried passing pointer but then when i modify array i get i also modify one in class cause they're the same one.

    So is there easy way to copy array of int to another one not using the loop for
    Or how can i get thet array from class in such manner that i can edit it without editing one in array.

    example:
    Code:
    class Example
    {
      public:
      Example();//let say it already sets values of array[0]=1 and array[1]=2
      ~Example();
    
    don't know what GetArray();//function passing array
    int GetArray[1]();//which returns array[1]
    
    
      private:
      int array[2];
    }
    and now i have some function

    Code:
    int Whatdifferenc(int number)
    {
      class Example exm;
      int array2[2],result;
      //passing array from exm to array2
      array2[1]=number;
      result=exm.GetArray[1]()-array2[1];
      return result;
    }
    Hmm i hope someone will understand my problem.I've made quite a mass not questin but i don't know how to state it clearly

  2. #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    I'm not sure if I understood you correctly. But it seems what you need to know is how to pass arrays as arguments to functions and how to return arrays from functions and you are aso having doubts on how arrays are created and initialized.

    Lets declare an array of ints and initialize it:

    Code:
    int myarray[5] = {11,12,13,14,15};
    
    // or
    
    int myarray[] = {11,12,13,14,15}; // dimensions are taken from the initialization
    Arrays cannot be copied or assigned.

    Code:
    int anotherarray[] = myarray; // error. cannot assign one array to another.
    int anotherarray[](myarray); // error. Cannot initialize an array as a copy of another.
    So the "trick" (there's not really a trick. It's how you should do it), is to keep the array size as a const variable and to use for loops to initialize arrays from other arrays.

    Code:
    const int ARRAY_SIZE = 5;
    int myarray[ARRAY_SIZE] = {11,12,13,14,15};
    
    int anotherarray[ARRAY_SIZE];
    for (int i = 0; i != ARRAY_SIZE; ++i) {
        anotherarray[i] = myarray[i];
    }
    When passing arrays to functions the array_size becomes a fundamental aspect of array usage. How would a function know the array size without this very important piece of information be passed to it? It wouldn't. So, the size of the array has to make it's way onto the function parameters list.

    Let's create a function that adds some value to each element of an array.

    Code:
    void add_to_elements(int* arr, const int size, int value) {
        // arr is a pointer to int (read below)
        // size is the size of the array passed
        // value is the value to add to each element
    
        for (int i = 0; i != size; ++i) {
            arr[i] += value;
        }
    }
    int* refers to a pointer to int. This is an important concept when passing arrays to functions. An array name is automatically converted to a pointer to the first element. As you will see below, you pass the array by simply using its name. Thus the function must be declared as expecting a pointer to the first element of the array. Since the array stores ints, your parameter must be a pointer to int. To call the function:

    Code:
    int someval = 12;
    const int ARRAY_SIZE = 5;
    int myarray[ARRAY_SIZE] = {11,12,13,14,15};
    
    add_to_elements(myarray, ARRAY_SIZE, 5); // Ok.
    add_to_elements(someval, ARRAY_SIZE, 5); // Error!
    As you see the array is passed like any other variable. You just put its name. But contrary to other variables, when just named, an array is converted to a pointer to int. The second call is an error. someval is an int, not a pointer to int, thus this call gets immediatly flagged by the compiler.

    The reason why I'm making a mention to it is because a nasty error can occur from using functions that operate on arrays with non arrays as arguments. Change the first line of the previous code to this:

    Code:
    int val = 12;
    int* someval = &val;
    someval is now a pointer to int. Your compiler will happily proceed without an error. But what have you done! When you run the program, the function will be called and this bit inside the function definition will wreak havoc:

    Code:
        for (int i = 0; i != size; ++i) {
            arr[i] += value;
        }
    The program will crash and you won't know any better. For this reason some people prefer to declare their functions that operate on arrays only like this:

    Code:
    void add_to_elements(int arr[], const int size, int value)
    It at least helps to remind that arr is an array. However it has the side-effect of making the less attentive think that they are passing an array to a function. They aren't. They are passing still a pointer to the first element. Technically you can't pass arrays to functions. Although we say you do, the reality is that you are passing a pointer to the first element.

    So, now you already have a pretty good idea on how to pass arrays to functions. But how about returning arrays? You can't. You can however return a pointer to the first element of the array or the element itself.

    Code:
    int get_array_element(int* arr, int elem) {
            return arr[elem];
    }
    
    int* get_pointer to_first_array_element(int* arr, const int ARRAY_SIZE) {
      // do whatever you want to do to the array
      return arr;  // return the array name which is converted to a pointer to the first element.
    }
    Do note however that on the first function if elem is bigger than the array size you will be over the array boundaries, generating a nasty bug. So your code should check, prior to calling the function that elem is correct.

    And I guess this pretty much covers what you want to do.
    Last edited by Mario F.; 11-08-2006 at 09:27 AM.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by baniakjr
    My problem looks like that i have class wich have some array and i need to pass it somwhere alse. How to do it? I've tried passing pointer but then when i modify array i get i also modify one in class cause they're the same one.

    So is there easy way to copy array of int to another one not using the loop for
    Or how can i get thet array from class in such manner that i can edit it without editing one in array.
    Use a vector. That's the easy way.

    The hard way is to allocate memmory for you a new array and copy your array into it. Then pass the new array to the function. (or convercely, you could allocate the new array inside the function) But you have to be sure to free the memmory when you are done with it. Yes, this would generally use a for loop.

    example:
    Code:
    class Example
    {
      public:
      Example();//let say it already sets values of array[0]=1 and array[1]=2
      ~Example();
    
    don't know what GetArray();//function passing array
    int GetArray[1]();//which returns array[1]
    
    
      private:
      int array[2];
    }
    and now i have some function

    Code:
    int Whatdifferenc(int number)
    {
      class Example exm;
      int array2[2],result;
      //passing array from exm to array2
      array2[1]=number;
      result=exm.GetArray[1]()-array2[1];
      return result;
    }
    Hmm i hope someone will understand my problem.I've made quite a mass not questin but i don't know how to state it clearly
    Your example won't work because you can't use brackets in a function identifier.
    Besides that your example would work just fine.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  4. #4
    Registered User
    Join Date
    Sep 2005
    Posts
    20
    Thanks for answers.They're quit helpfull.Now i know that i always pass a pointer not an array to function and that i have to make a copy to distinguish them.

    And my second question is.Are there any other ways to copy one array to another other then
    Code:
    for (int i = 0; i != ARRAY_SIZE; ++i) {
        anotherarray[i] = myarray[i];

    Ok i know that my previous post was a little bit messed up(because my english and because i was tired).So here's something to streight it up.What i now wont realy to do is an accesor inside a class that will pass the pointer to the copy of array that is a private data of class(or any other way to pass that array).

    Code:
    class Example
    {
      public:
      Example();
      ~Example();
    
      int* GetArray();//function passing pointer to copy of array
    
    
      private:
      int array[2];
    }
    I forgot about memory allocating so i will try it and I'm completly unfamiliar with vectors so if anyone could explein or tell me where to look i'll be greatefull.

  5. #5
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    > And my second question is.Are there any other ways to copy one array to another other then [code showing a for loop]

    Yes. You can use memcpy().

    Code:
    const int SIZE = 5;
    int myarray[size] = {12,13,14,15,16};
    int otherarray[size];
    
    memcpy(otherarray, myarray, SIZE);
    Is it safe? Nope. The function has no error reporting mechanism. If otherarray number of elements is smaller than SIZE, the function returns undefined behavior. On some compilers it may crash during run-time (good), on some compilers the program keeps running (bad!), on other compilers you get an error at compile time(Excellent!).

    Use for. And if you don't like it, use while
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  6. #6
    Registered User
    Join Date
    Sep 2005
    Posts
    20
    thanks a lot.Your help was most usefull.Now everything works fine.finaly i used mem allocation and for loop.

  7. #7
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    Yes. You can use memcpy().
    For PODs only.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning Array
    By baffa in forum C Programming
    Replies: 26
    Last Post: 02-01-2008, 10:08 AM
  2. Returning an Array
    By mmarab in forum C Programming
    Replies: 10
    Last Post: 07-19-2007, 07:05 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Replies: 6
    Last Post: 10-21-2003, 09:57 PM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM