interchanging arrays in c

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aphrodite
    New Member
    • Jan 2007
    • 3

    interchanging arrays in c

    How do I interchange two arrays? I tried arr[i]=arr[j] but I get the error: "ISO-C++ forbids assignement of arrays.
    Just to mention it, I'm trying to sort an array of strings in ascending order. The array is declared: char arr[20][20] because it's names that I have in it.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Assuming that the arrays are the same size then your best bet is memcpy

    memcpy( arr[i], arr[j], sizeof arr[i]);

    Comment

    • horace1
      Recognized Expert Top Contributor
      • Nov 2006
      • 1510

      #3
      Originally posted by aphrodite
      How do I interchange two arrays? I tried arr[i]=arr[j] but I get the error: "ISO-C++ forbids assignement of arrays.
      Just to mention it, I'm trying to sort an array of strings in ascending order. The array is declared: char arr[20][20] because it's names that I have in it.
      in C and C++ the name of an array refers to the address of the first element in memory so you cannot do an assignment
      Code:
      char arr[20][20]={0};
      arr[i]=arr[j];
      you have to copy the elements one at a time, e.g.
      Code:
          for (int k=0; k<20; k++) arr[i][k]=arr[j][k];
      or you can use memcpy(), see

      Comment

      • willakawill
        Top Contributor
        • Oct 2006
        • 1646

        #4
        Originally posted by aphrodite
        How do I interchange two arrays? I tried arr[i]=arr[j] but I get the error: "ISO-C++ forbids assignement of arrays.
        Just to mention it, I'm trying to sort an array of strings in ascending order. The array is declared: char arr[20][20] because it's names that I have in it.
        Hi. Perhaps you are asking about swapping 2 elements of the array in a sort

        Code:
        //swap
        char arTmp[20];
        if (strcmp(ar1[0], ar1[1]) < 0) {
           strcpy(arTmp, ar1[0]);
           strcpy(ar1[0], ar1[1]);
           strcpy(ar1[1], arTmp);
        }

        Comment

        Working...