【问题标题】:Correct output only when debugging仅在调试时正确输出
【发布时间】:2014-07-25 11:00:05
【问题描述】:

我在用 C 语言完成家庭作业时遇到了一些问题。 我遇到了一个奇怪的问题,程序在使用调试器运行时给了我预期的输出,但是在正常运行时我得到了一个奇怪的结果。

该程序采用 2 个多项式并打印 2 个的和和乘积。 多项式的输入简单的就是[coefficient] [power] [coefficient] [power]等形式。。

总和打印正确。下面是用到的函数:

void printPolynome(MONOM* poly, int size)
 {
     int i;

     for (i=0; i<size; i++)
     {
         if ((poly[i].coefficient > 0)&&(i != 0))
             printf("+");

         if (poly[i].power == 0)
             printf("%d", poly[i].coefficient);
         else if (poly[i].power == 1)
         {
             printf("%dx", poly[i].coefficient);
         }
         else
            printf("%dx^%d", poly[i].coefficient, poly[i].power);
     }

     if (size == 0)
         printf("0");
 }

void printSumPolynomes(MONOM *p1, int s1, MONOM *p2, int s2)
 {
     int phSize = s1+s2;
     MONOM* res = (MONOM*) malloc(phSize * sizeof(MONOM)); // Worst case size of result polynome

     int i=0;
     int j=0;
     int resInd=0;
     int finalSize = 0;

     while ( (i<s1) && (j<s2) )
     {
         if (p1[i].power > p2[j].power)
         {
             res[resInd] = p1[i];
             i++;
         }
         else if (p1[i].power < p2[j].power)
         {
             res[resInd] = p2[j];
             j++;
         }
         // If numbers have the same power, sum the coefficients.
         else if (p1[i].power == p2[j].power)
         {
             if (p1[i].coefficient + p2[j].coefficient != 0)
             {
                 p1[i].coefficient += p2[j].coefficient;
                 res[resInd] = p1[i];
                 j++;
                 i++;
             }
             else
             {
                 j++;
                 i++;
                 resInd--;
                 finalSize--;
             }
         }

         resInd++;
         finalSize++;
     }
     // Take care of leftovers and add them to array.
     while (i < s1)
     {
         res[resInd] = p1[i];
         resInd++;
         i++;
         finalSize++;
     }
     while (j < s2)
     {
         res[resInd] = p2[j];
         resInd++;
         j++;
         finalSize++;
     }

     // Clip array if needed.
     if (phSize > finalSize)
        res = (MONOM*) realloc(res, finalSize * sizeof(MONOM));

     printPolynome(res, finalSize);
     free(res);
 }

void printMulPolynomes(MONOM *p1, int s1, MONOM *p2, int s2)
{
    int phSize = s1*s2;
    int i;
    int j;
    int resInd = 0;
    int mulSize = 0;

    MONOM* res = (MONOM*) malloc (phSize * sizeof(MONOM));

    for (i=0; i<s1; i++)
    {
        for (j=0; j<s2; j++)
        {
            res[resInd].coefficient = p1[i].coefficient * p2[j].coefficient;
            res[resInd].power = p1[i].power + p2[j].power;
            mulSize++;
            resInd++;
        }
    }

    // use sortInput function to sort the result.
    sortInput(res,mulSize);

    // calculate number of monoms in result
    i=0;
    mulSize = 0;
    while (res[i].power >= 0)
    {
        mulSize++;
        i++;
    }

    if (phSize > mulSize)
        res = (MONOM*) realloc(res, mulSize * sizeof(MONOM));

    printPolynome(res, mulSize);
    free(res);
}

这里是 getPolynome 函数:

MONOM* getPolynome(int* logSize)
 {
    int phSize = INIT_SIZE; // physical size
    int initLogSize = 0; // logical size of initial input
    int ch;
    int i = 0;
    int j = 0;
    int countLegalMonoms = 0;
    int countNums = 0;
    char* marker;
    char* userInput;
    char* token;
    MONOM* poly;
    BOOL sumFlag;
    int currCoef, currPow; // Variables for current coefficient and power input

    // Get the first char of input
    ch = getchar();

    // Create array for raw user input
    userInput = (char*) malloc (phSize * sizeof(char));

    while (ch != EOL)
    {
        if (phSize == initLogSize)
        {
            phSize *= 2;
            userInput = (char*) realloc (userInput, phSize);

        }

        userInput[i] = ch;
        initLogSize++;
        i++;

        // get next input
        ch = getchar();
    }
    userInput[i] = EOS;

    // Check how many numbers are in the array.
    marker = userInput;
    while (*marker != EOS)
    {
        if ( (*marker == ' ') || (*marker != ' ')&&(*(marker+1) == '\0') )
            countNums++;

        marker++;
    }

    // Create monoms array - a polynome
    poly = (MONOM*) malloc (countNums/2 * sizeof(MONOM));

    // Take the first token
    token = strtok(userInput, " ");

    while (token != NULL)
    {
        sumFlag = FALSE;

        sscanf(token, "%d", &currCoef);
        token = strtok(NULL, " ");
        sscanf(token, "%d", &currPow);

        // Check if the current power exists.
        for (i=0; i < countNums/2; i++)
        {
            if (poly[i].power == currPow)
            {
                poly[i].coefficient += currCoef;
                sumFlag = TRUE;

                // Check if the coeeficient sums to 0
                if (poly[i].coefficient == 0)
                    poly[i].power = COEF_NULL_FLAG; // Will be used later to remove from array.
            }
        }

        // Summation was not performed. Creating a new monom.
        if (sumFlag == FALSE)
        {
            poly[j].power = currPow;
            poly[j].coefficient = currCoef;
            j++;
        }

        token = strtok(NULL, " ");
    }


    // We now want to sort the array.
    sortInput(poly, j);

    // Count how many legal monoms are currently in the array
    for (i=0; i < j; i++)
    {
        if (poly[i].power != COEF_NULL_FLAG)
            countLegalMonoms++;
    }

    // Finished dealing with data - clip the array
    poly = (MONOM*) realloc (poly, countLegalMonoms * sizeof(MONOM));

    *logSize = countLegalMonoms;
    return poly;
}

这是主要功能:

#define _CRT_SECURE_NO_WARNINGS
#define INIT_SIZE 2
#define EOL '\n'
#define EOS '\0'
#define COEF_NULL_FLAG -1
#define TRUE 1
#define FALSE 0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct monom{ 
    int coefficient; 
    int power; 
}MONOM;

typedef int BOOL;

...

void main() {
    int myLogSize1, myLogSize2;
    MONOM* myPoly1;
    MONOM* myPoly2;

    printf("Please enter first polynome:");
    myPoly1 = getPolynome(&myLogSize1);
    printf("Please enter second polynome:");
    myPoly2 = getPolynome(&myLogSize2);

    printf("\n");
    printf("The sum of polynomes is: ");
    printSumPolynomes(myPoly1, myLogSize1, myPoly2, myLogSize2);
    printf("\n");
    printf("The multiplication of polynomes is: ");
    printMulPolynomes(myPoly1, myLogSize1, myPoly2, myLogSize2);

    printf("\n");


    free(myPoly1);
    free(myPoly2);
}

这是我为以下输入得到的输出:

Please enter first polynome:-2 2 2 3
Please enter second polynome:2 2

The sum of polynomes is: 2x^3
The multiplication of polynomes is: 4x^5-4x^4-33686019x^50865+5198872x^5177540+1
389377768x^201377471+5340200x^5349952+1428628924x^274+24x^2
Press any key to continue . . .

非常感谢您的帮助,我真的找不到输出中所有额外垃圾的来源。

【问题讨论】:

  • 向我们展示函数“getPolynome”
  • 我已将其添加到我的原始帖子中。
  • 代码太长....!!!你先调试一下。
  • phSize == initLogSize...userInput[i] = EOS; : 分配内存时不考虑。
  • while (i&lt;resInd &amp;&amp; res[i].power &gt;= 0)

标签: c arrays pointers memory struct


【解决方案1】:

我认为问题出在 void printSumPolynomes(MONOM *p1, int s1, MONOM *p2, int s2):

// calculate number of monoms in result
i=0;
mulSize = 0;
while (res[i].power >= 0)
{
    mulSize++;
    i++;
}

只有在遇到小于零的幂时才会停止。因为你没有初始化你的数组 res 而只是做了

MONOM* res = (MONOM*) malloc (phSize * sizeof(MONOM));

它将扫描未分配的内存并导致垃圾输出。

AIUI 你甚至不需要那个代码,因为你的最终尺寸已经在 mulSize 中了

编辑: 实际上 mulSize 是 s1*s2,虽然这是多项式的最终大小,但您可以考虑将项与相应的幂相结合,就像在 getPolynome() 中所做的那样

编辑: 没有显式初始化 res 数组不会导致这里出现问题,因为实际上所有条目 (2) 都将设置正确的值,但计算单声道数的循环不会在数组末尾终止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    相关资源
    最近更新 更多