Weird array mutation!!

This is a discussion on Weird array mutation!! within the C Programming forums, part of the General Programming Boards category; Hi, ( Please dont be discouraged from the length of this post, I would greatly appreciate any pointers, advice or ...

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    3

    Weird array mutation!!

    Hi,

    (Please dont be discouraged from the length of this post, I would greatly appreciate any pointers, advice or solution.)

    I have programmed a bit but I'm fairly new to C, (I'm spoiled from higher level languages, so obviously you can tell this is hurting me). Anyways, the problem I'm having lies in the add_polynom function.

    Basically the point of the function is to simply add two polynomials.
    Everything is fine and dandy until I start adding a second poly
    onto the first. For some reason values of the first array also gets modified, and I have debugged for days with no solution.

    I have bolded where I think the problem lies.

    Intended Algo: Add coefficients with same exponent. Next detect if any exponent that is in ex2 exists in ex1. If there are any, make room for the needed exp that are to be put in coef1 and ex1, then put 'em in. Finally put the array in order (not done yet).

    Code:
    Ex:
    in a separate Main file.
    
        int coef1[] = {3, 4, 5, 6, 3};
        int ex1[] =    {3, 1, 2, 0, 5};
        int coef2[] = {4, 5, 6, 7, 9};
        int ex2[]  =   {4, 1, 2, 0, 8};
        dataSize = 5; // Indicate the size of the arrays
        add_polynom(coef1, ex1, coef2, ex2);
    
    output :
    
    ADD: 
    int coefficient1[] =        {3, 4, 5, 6, 3}; 
           int exponent1[] =   {3, 1, 2, 0, 5};
                         PLUS
           int coefficient2[] = {4, 5, 6, 7, 9};
           int exponent2[]  =  {4, 1, 2, 0, 8};
    
    ADD coefficient when exponents of both arrays are the same and put that result in coefficient1
    coefficient1   [3     9    11   13     3]
    exponent1     [3     1     2    0      5]
    
    2 indices of exponent2 are not in exponent1
    coefficient2   [4     5     6    7      9]
    exponent2     [4     1     2    0      8]
    
    coefficient 1 must be expanded to add the two missing exponents into exponent1 and coefficient1 
    coefficient1   [3     9    11   13     3  rndNum    rndNum]
    exponent1     [3     1     2    0      5  rndNum    rndNum]
    
    Copy over the required values (this is what is expected final answer)
    coefficient1   [3     9    11   13     3    4       9]
    exponent1    [3      1     2     0     5    4       8]
    
    This is what is happening
    coefficient     [4      8    11   13     3    4     9]
    exponent       [3     1     2     0     5    4      8]
    For some reason 4 and 8 from exponent are copied over to the beginning indices of coefficient. WHYY?? It's really got me down.
    I would appreciate any help.


    Code:
    int dataSize;
    /*
      Initialize all coefficients and exponents of the polynomial to zero.
     */
    void init_polynom( int coeff[ ], int exp[ ] )
    {
        int j;
        for (j=0; j<=ASIZE-1; j++)
        {
            coeff[j] = 0;
            exp[j]= 0;
            //exp[j] = 0;
        }
    }  /* end init_polynom */
    
    
    void printNumArray(int a[])
    {
        int i;
        printf("[");
        /* (ASIZE/8)-1*/
        for (i=0; i<= dataSize - 1; i++)
        {
            if (i!= dataSize - 1)
            printf("%d\t", a[i]);
            else
            printf("%d", a[i]);
        }
        printf("]");
    }
    
    
    /*
      Get inputs from user using scanf() and store them in the polynomial.
     */
    void get_polynom( int coeff[ ], int exp[ ] )
    {
        int tmpArr[ASIZE];
        int in;
        int x;
        int dctr;
    
    
        scanf("%d", &in);
        dctr = in;
        dataSize = in;
        for (x=0; x<= ((dctr*2)-1); x++)
        {
            scanf("%d", &in);
            tmpArr[x] = in;
        }
    
    
        for (x=0; x<= dctr-1; x++)
        {
            coeff[x] = tmpArr[2*x];
            exp[x] = tmpArr[(2*x)+1];
        }
    
    
        //printf("coeff:\t");
        //printNumArray(coeff);
        //printf("\nexp:\t");
        //printNumArray(exp);
    
    
    }  /* end get_polynom */
    
    
    /*
        Check if the coefficients of all the entries sum up to 0.
    */
    int zero_sum(int coeff[])
    {
        int i;
        int sum;
    
    
        for (i=0; i<=dataSize-1; i++)
            sum += coeff[i];
    
    
        if (sum == 0)
            return 1;
        else
            return 0;
    }
    
    
    /*
      Convert the polynomial to a string s.
     */
    void polynom_to_string( int coeff[ ], int exp[ ], char s[ ] )
    {
        /*
        int cr_coeff;
        int cr_exp;
        int i;
    
    
        if (zero_sum(coeff) == 0) /* Sum is not zero
        {
            for (i=0; i<= dataSize-1; i++)
            {
                cr_coeff = coeff[i];
                cr_exp = exp[i];
                if (cr_coeff != 0)
                {
                    if (cr_coeff == 1)
                    {
                        if (cr_exp == 1)
                        {
                            /* coef and exp are both 1
                            s += ((char)cr_coeff)+"x^"+((char)cr_exp)+"+";
                        }
                        else
                        {
                            /* only coeff is one
                            s += cr_coeff"x^"+cr_exp+"+";
                        }
                    }
                    else
                    {
                        if (cr_exp == 1)
                        {
                            /* only cr_exp is one
                            s += cr_coeff"x^"+cr_exp+"+";
                        }
                        else
                        {
                            /* Neither cr_exp or coeff are one
                            s += cr_coeff"x^"+cr_exp+"+";
                        }
    
    
                    }
    
    
                }
            }
        }
        else /* Sum is zero
        {
            s = "0";
            printf("%s", s);
        }
    
    
        printf("FINAL ANSWER->%s<-", s)*/
    }  /* end polynom_to_string */
    
    
    
    
    
    
    
    
    /*
      Evaluate the polynomial for the value of x and store the result p(x) in variable result.
     */
    void eval_polynom( int coeff[ ], int exp[ ], double x, double *result)
    {
        int i, j;
        double s, ml;
    
    
        for(i=0;i<=dataSize-1;i++)
        {
            ml = x;
    
    
            // Exponent  Operation
            for (j=0; j<=exp[i]-2; j++)
            {
                ml *= x;
            }
    
    
            // Coefficient Multiplication
            ml *= coeff[i];
    
    
            //printf("\nreswithcof:%f\n", ml);
            s += ml;
            //("sum:%f\n", s);
        }
    
    
        *result = s;
    }  /* end eval_polynom */
    
    
    
    
    
    
    /*
      Add two polynomials and the result is stored in the first polynomial (arrays co1[] and ex1[]).
     */
    void add_polynom( int co1[ ], int ex1[ ], int co2[ ], int ex2[ ] )
    {
        //addOp(&co1, &ex1, &co2, &ex2);
        int i,j;
    
    
        // Add all the data from col2 to col1 and make col2 entries found 0
        for (i = 0; i<= dataSize-1; i++)
        {
    
    
            for (j = 0; j <= dataSize-1; j++)
            {
                /* Check with one i polynomial  with all of j's polynomials */
                if (ex1[i] == ex2[j])
                {
                    //printf("ex1 == ex2");
                    co1[i] = co1[i] + co2[i];
                    co2[i] = 0;
                }
            }
        }
    
    
    
    
        // Loop through col2 and see if they are missing columns
        int msCtr = 0; // Number of missing items counter;
        int tCtr = 0; // Temporary counter
        int m, n;
    
    
        int d_ind_ex[dataSize];
        int d_ind_co[dataSize];
    
    
        for (m = 0; m <= dataSize-1; m++)
        {
            for (n = 0; n <= dataSize-1; n++)
            {
                printf("ex2->%d<- ex1->%d<-\n", ex2[m], ex1[n]);
                if (ex2[m] == ex1[n])
                {
                    tCtr++;
                }
    
    
                if ((n == dataSize-1) && (tCtr == 0))
                {
                    printf("An exponent %d not found in ex1\n", ex2[m]);
                    d_ind_ex[msCtr] = ex2[m];
                    d_ind_co[msCtr] = co2[m];
                    msCtr++;
                   // tCtr = 0;
                }
            }
            tCtr = 0;
        }
    
    
        d_ind_ex[msCtr];
        d_ind_co[msCtr];
    
    
        int k = 5;
        int l, jj;
        // K starts at end of co1 and ends at missing char index size
    
    
      // Add the new data entries to co1 and ex1
        for (k = i, jj = 0; k <= i+msCtr-1; k++, jj++)
        {
            dataSize++;
    
    
            printf("i>%d< k>%d< jj>%d<, d_ind_co>%d<,  
            d_ind_ex>%d<\n", i, k, jj, d_ind_co[jj], d_ind_ex[jj]);
            printf("\n\n\n\nbefore ->\n");
            printNumArray(co1);
            printf("\n");
            printNumArray(ex1);
            printf("\nK val%d, jj val%d<", k, jj);
    
    
      co1[k] = d_ind_co[jj];
    
    
            printf("\n");
            printNumArray(co1);
            printf("\n");
            printNumArray(ex1);
            printf("\n<-");
    
    
            printf("k>%d<, BBB%dBBB", k, ex1[k]);
    
    
     ex1[k] = d_ind_ex[jj];
    
    
            printf("\nafter->\n");
            printNumArray(co1);
            printf("\n");
            printNumArray(ex1);
            printf("\n<--\n\n\n");
    
    
        }
    
    
        printf("co1:\n");
        printNumArray(co1);
        printf("\nex1:\n");
        printNumArray(ex1);
    
    
        printf("\n\nco2:\n");
        printNumArray(co2);
        printf("\nex2:\n");
        printNumArray(ex2);
    
    
    
    
    }  /* end add_ polynom */
    
    
    /************* END OF FILE ********************/
    Last edited by neden; 10-12-2011 at 01:45 AM.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    There's a LOT wrong with this code...

    I suggest you get yourself some decent tutorials on C and work them page by page and exercise by exercise... You'll be glad you did.

    First you need to understand that C is a language with absolutely no knowledge of strings...
    Instead you are working with character arrays that are either defined sizes or allocated on the heap with Malloc...

    You simply can't do any of these in C...
    Code:
           /* coef and exp are both 1
           s += ((char)cr_coeff)+"x^"+((char)cr_exp)+"+";
    
          /* only coeff is one
          s += cr_coeff"x^"+cr_exp+"+";
       
          /* only cr_exp is one
          s += cr_coeff"x^"+cr_exp+"+";
    
          /* Neither cr_exp or coeff are one
         s += cr_coeff"x^"+cr_exp+"+";
    Also you are repeatedly using stuff like ...
    Code:
        for (m = 0; m <= dataSize-1; m++)
    This is better written as
    Code:
        for (m = 0; m < dataSize; m++)
    The difference being that datasize-1 does not have to be calculated every time through the loop and you're only using one comparison not two.

    Also... what is the value of sum when this loop starts?
    Code:
    int zero_sum(int coeff[])
    {
        int i;
        int sum;
    
    
        for (i=0; i<=dataSize-1; i++)
            sum += coeff[i];
    
       if (sum == 0)
            return 1;
        else
            return 0;
    }
    No, C does not initialize variables to 0 ... you have to do that yourself... int sum = 0;


    So... time to hit the books and actually learn C...

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    3
    Wow that was a fast reply, thank you I will take your advice. But as you know the add_poly prob is still there, any tips on that matter.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,980
    Quote Originally Posted by neden
    thank you I will take your advice. But as you know the add_poly prob is still there
    Take the advice by fixing the problems outlined first, then if there are still problems, post the updated code and tell us what problems remain.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Code:
      // Add the new data entries to co1 and ex1
        for (k = i, jj = 0; k <= i+msCtr-1; k++, jj++)
    What is the value of i at this point?
    What happens when you increment k?


    And what's with the weird exit clause? try... k < i +msctr

  6. #6
    Registered User
    Join Date
    Oct 2011
    Posts
    3
    Sorry I couldn't reply quicker, the last time I posted it was 5 AM in the morn..(lol)

    Anyways. To answer your question:

    Code:
    for (k = i, jj = 0; k <= i+msCtr-1; k++, jj++)
    Q)What is the value of i at this point?
    A) i is 5.

    Q) What happens when you increment k?
    A) Basically k starts at the position of coefficient1 and starts
    putting values in it.

    Code:
    Ex: Coefficient1 = {5 , 7, 9, 6, 3}
    In this situation k would start at index 5 (because it is currently empty) and start putting in data. The variable 'i' will always start at the next position index after the last data that was put.

    Q) And what's with the weird exit clause? try... k < i +msctr
    A) The for-loop just before this code, checks for the number of missing exponents that are in coefficient2 but not in coefficient 1. The variable msctr calculates this result.

    Example

    Code:
    int    coefficient1[] =     {3, 4, 5, 6, 3};  
    int exponent1[] =    {3, 1, 2, 0, 5};                    
                 PLUS       
    int coefficient2[] = {4, 5, 6, 7, 9};
    int exponent2[]  =   {4, 1, 2, 0, 8};

    Exponent1 and Exponent2 have 1, 2, and 0 in common. So the 4 and 8 in exponent2 are the only things not in exponent1 thus msctr's value is 2 at the current point in the program.


    Here's the Updated Code:

    Code:
    int dataSize;
    /*
      Initialize all coefficients and exponents of the polynomial to zero.
     */
    void init_polynom( int coeff[ ], int exp[ ] )
    {
        int j;
        for (j=0; j<ASIZE; j++)
        {
            coeff[j] = 0;
            exp[j]= 0;
            //exp[j] = 0;
        }
    }  /* end init_polynom */
    
    
    void printNumArray(int a[])
    {
        int i;
        printf("[");
        /* (ASIZE/8)-1*/
        for (i=0; i< dataSize; i++)
        {
            if (i!= dataSize - 1)
            printf("%d\t", a[i]);
            else
            printf("%d", a[i]);
        }
        printf("]");
    }
    
    
    /*
      Get inputs from user using scanf() and store them in the polynomial.
     */
    void get_polynom( int coeff[ ], int exp[ ] )
    {
        int tmpArr[ASIZE];
        int in;
        int x;
        int dctr;
    
    
        scanf("%d", &in);
        dctr = in;
        dataSize = in;
        for (x=0; x< (dctr*2); x++)
        {
            scanf("%d", &in);
            tmpArr[x] = in;
        }
    
    
        for (x=0; x< dctr; x++)
        {
            coeff[x] = tmpArr[2*x];
            exp[x] = tmpArr[(2*x)+1];
        }
    
    
    }  /* end get_polynom */
    
    
    /*
        Check if the coefficients of all the entries sum up to 0.
    */
    int zero_sum(int coeff[])
    {
        int i;
        int sum = 0;
    
    
        for (i=0; i<dataSize; i++)
            sum += coeff[i];
    
    
        if (sum == 0)
            return 1;
        else
            return 0;
    }
    
    
    
    
    /*
      Evaluate the polynomial for the value of x and store the result p(x) in variable result.
     */
    void eval_polynom( int coeff[ ], int exp[ ], double x, double *result)
    {
        int i, j;
        double s, ml;
    
    
        for(i=0;i<dataSize;i++)
        {
            ml = x;
    
    
            // Exponent  Operation
            for (j=0; j<exp[i]-1; j++)
            {
                ml *= x;
            }
    
    
            // Coefficient Multiplication
            ml *= coeff[i];
    
    
            //printf("\nreswithcof:%f\n", ml);
            s += ml;
            //("sum:%f\n", s);
        }
    
    
        *result = s;
    }  /* end eval_polynom */
    
    
    
    
    
    
    /*
      Add two polynomials and the result is stored in the first polynomial (arrays co1[] and ex1[]).
     */
    void add_polynom( int co1[ ], int ex1[ ], int co2[ ], int ex2[ ] )
    {
        //addOp(&co1, &ex1, &co2, &ex2);
        int i,j;
    
    
        // Add all the data from col2 to col1 and make col2 entries found 0
        for (i = 0; i< dataSize; i++)
        {
    
    
            for (j = 0; j < dataSize; j++)
            {
                /* Check with one i polynomial  with all of j's polynomials */
                if (ex1[i] == ex2[j])
                {
                    //printf("ex1 == ex2");
                    co1[i] = co1[i] + co2[i];
                    co2[i] = 0;
                }
            }
        }
    
    
    
    
        // Loop through col2 and see if they are missing columns
        int msCtr = 0; // Number of missing items counter;
        int tCtr = 0; // Temporary counter
        int m, n;
    
    
        int d_ind_ex[dataSize];
        int d_ind_co[dataSize];
    
    
        for (m = 0; m < dataSize; m++)
        {
            for (n = 0; n < dataSize; n++)
            {
                printf("ex2->%d<- ex1->%d<-\n", ex2[m], ex1[n]);
                if (ex2[m] == ex1[n])
                {
                    tCtr++;
                }
    
    
                if ((n == dataSize-1) && (tCtr == 0))
                {
                    printf("An exponent %d not found in ex1\n", ex2[m]);
                    d_ind_ex[msCtr] = ex2[m];
                    d_ind_co[msCtr] = co2[m];
                    msCtr++;
                   // tCtr = 0;
                }
            }
            tCtr = 0;
        }
    
    
        d_ind_ex[msCtr];
        d_ind_co[msCtr];
    
    
        printf("\nmissingCtr->%d<-\n\n", msCtr);
        printf("val of col2->\n");
        printNumArray(d_ind_co);
        printf("\n<-end\n");
        printf("val of ex2->\n");
        printNumArray(d_ind_ex);
        printf("\n<-end\n\n");
    
    
        // Add the left out entries from col2 to the end of col1.
        printf("Val of i?%d\n", i);
    
    
        int k = 5;
        int l, jj;
        // K starts at end of co1 and ends at missing char index size
     
        printf("iEEEEE>%d<", i);
        for (k = i, jj = 0; k < i+msCtr; k++, jj++)
        {
            dataSize++;
    
    
            printf("i>%d< k>%d< jj>%d<, d_ind_co>%d<, d_ind_ex>%d<\n", i, k, jj, d_ind_co[jj], d_ind_ex[jj]);
            printf("\n\n\n\nbefore ->\n");
            printNumArray(co1);
            printf("\n");
            printNumArray(ex1);
            printf("\nK val%d, jj val%d<", k, jj);
    
    
            co1[k] = d_ind_co[jj];
    
    
            printf("\n");
            printNumArray(co1);
            printf("\n");
            printNumArray(ex1);
            printf("\n<-");
    
    
            printf("k>%d<, BBB%dBBB", k, ex1[k]);
    
    
            ex1[k] = d_ind_ex[jj];
    
    
            printf("\nafter->\n");
            printNumArray(co1);
            printf("\n");
            printNumArray(ex1);
            printf("\n<--\n\n\n");
    
    
            // If entry found dont forget to dataSize++;
        }
    
    
     
        printf("co1:\n");
        printNumArray(co1);
        printf("\nex1:\n");
        printNumArray(ex1);
    
    
        printf("\n\nco2:\n");
        printNumArray(co2);
        printf("\nex2:\n");
        printNumArray(ex2);
    
    
    }  /* end add_ polynom */
    
    
    
    
    /************************** END OF FILE ***************************/
    Last edited by neden; 10-12-2011 at 11:17 AM.

  7. #7
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    I'm not sure what you're expecting us to do, when you're only posting code fragments that won't even compile.
    How are we even supposed to guess at what array overrun horrors you have, when we can't even see what ASIZE is declared as (for example).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. weird array initialization
    By dayalsoap in forum C Programming
    Replies: 2
    Last Post: 08-25-2010, 10:20 PM
  2. Mutation
    By peacealida in forum C Programming
    Replies: 1
    Last Post: 04-04-2008, 09:19 AM
  3. weird two dimensional array
    By stevesmithx in forum C Programming
    Replies: 4
    Last Post: 09-18-2007, 07:55 PM
  4. Mutation Operator
    By Cdrwolfe in forum C++ Programming
    Replies: 10
    Last Post: 07-11-2006, 09:41 AM
  5. Weird error when using array
    By axr0284 in forum C++ Programming
    Replies: 3
    Last Post: 09-12-2005, 06:34 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21