堆栈代码无法运行

时间:2018-03-01 09:55:30

标签: c data-structures

我正在做作业。我已经完成了代码,但当我回头看时,我发现我错过了进入有效和无效堆栈的分数。

所以我尝试修改代码但修改后的代码将编译但不运行。我不知道为什么。有人能帮我吗。非常感谢。

/*
Question 1
This program uses an array applications.
*/

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



//declare struct node as STK
struct node
{
    int top;
    int element[100];
};  

struct node *valid,*invalid;//declare two stack for valid score and invalid score


int main()
{

valid->top=-1;//create empty stack for valid score
invalid->top=-1;
int size, score[size]; //variables for array purposes
int tempMin=100, tempMax=0; //variables for lowest and highest marks
int i,total=0,validCounter=0,invalidCounter=0,countH1=0,countH2=0,countH3=0,countH4=0,countH5=0; //variables for counting purposes
float average; //variable for average

printf ("STUDENTS MARK ENTERING SESSION\n");
printf ("Enter total number of student: ");
scanf ("%d", &size);
printf("\n");

/*Get Marks form User*/
printf ("Enter MID-SEMESTER Test Score:\n");

for (i=0;i<size;i++)
{
    printf("Test Score #%d: ",i+1);
    scanf ("%d",&score[i]);
    if((score[i]<0) ||(score[i]>100))
    printf("Error:Invalid score entered!\n");
}

printf ("\nThe MID-SEMESTER Test Score");


for (i=0;i<size;i++)
{
    if ((score[i]>=0) && (score[i]<=100))
    {
        valid->element[++valid->top]=score[i];//write the score into valid stack
        printf("%d ",score[i]);
        total+=score[i];
        validCounter=validCounter+1;

        if (score[i]<=tempMin)
        {
            tempMin=score[i];
        }

        if (score[i]>=tempMax)
        {
            tempMax=score[i];
        }
    }
}
/*Print Valid Score*/
printf ("\n\nValid score: ");
if(valid->top==-1)
printf("Empty valid score stack");
else
{
    for(i=valid->top;i>=0;i--)
    printf("%d\t",valid->element[i]);
    printf("\n");
}


for (i=0;i<size;i++)
{
    if ((score[i]<0) || (score[i]>100))
    {
        invalid->element[++invalid->top]=score[i];//write the score into invalid stack
        printf("%d ",score[i]);
        invalidCounter=invalidCounter+1;
    }
}
/*Print Invalid Score*/
printf ("\nInvalid score: ");
if(invalid->top==-1)
printf("Empty invalid score stack");
else
{
    for(i=invalid->top;i>=0;i--)
    printf("%d\t",invalid->element[i]);
    printf("\n");
}

/*Print Average Score*/
average=total/validCounter;
printf("\nAverage score: %.2f", average);

/*Print Lowest Score*/
printf ("\nLowest score: %d", tempMin);

/*Print Highest Score*/
printf ("\nHighest score: %d", tempMax);

/*Print Histogram*/
for (i=0;i<size;i++)
{
    if ((score[i]>=80) && (score[i]<=100))
    {
        countH1=countH1+1;
    }
    else if ((score[i]>=60) && (score[i]<=79))
    {
        countH2=countH2+1;
    }

    else if ((score[i]>=50) && (score[i]<=59))
    {
        countH3=countH3+1;
    }
    else if ((score[i]>=30) && (score[i]<=49))
    {
        countH4=countH4+1;
    }
    else if ((score[i]>=0) && (score[i]<=29))
    {
        countH5=countH5+1;
    }
}
printf ("\nHistogram: ");
printf ("\n\t[80-100]: %d", countH1);
printf ("\n\t[60-79]:  %d", countH2);
printf ("\n\t[50-59]:  %d", countH3);
printf ("\n\t[30-49]:  %d", countH4);
printf ("\n\t[0-29]:   %d", countH5);

/*Print Number of Invalid Score*/
printf("\nTotal number of invalid score: %d", invalidCounter);
}

2 个答案:

答案 0 :(得分:2)

这足以让您的程序调用未定义的行为:

struct node

在(1)中,您声明了两个指向struct node _valid, _invalid; struct node valid = &_valid, invalid = &_invalid; 的指针,但让它们未初始化。由于它们具有静态存储,因此编译器将默认将它们初始化为NULL。

在(2)中,您取消引用正式为UB的NULL指针。

快速修复可能是:

int size, score[size];

但你应该想知道间接是否相关......

在评论中告诉你还有其他问题:

  • public interface VehicleRepository extends JpaRepository<Vehicle, String> { @Query("select v.sourceModule as sourceModule, count(v) as vehicleCount from Vehicle v group by v.sourceModule") List<Object[]> sourceModuleStats(); } 使用未初始化的可变大小
  • 可能是其他人......

答案 1 :(得分:0)

当你想操纵指针指向的结构时, 那些结构应该存在于记忆中。

<script>
      var inner_data=document.getElementById('container').innerHTML;
      $(".mytest_class").replaceWith('<p class="mytest_class">Welcome World</p>');
      // after changing value, again get the value from html.
      var inner_data=document.getElementById('container').innerHTML;
      console.log(inner_data);
</script>

可能的解决方案,在堆或堆栈上分配内存:

struct node *valid,*invalid; // Two pointers pointing to NULL

int main()
{
valid->top=-1;    //  run time error: NULL->top (dereferencing NULL)
invalid->top=-1;  //  run time error: NULL->top
//...
}

注意:Do I cast the result of malloc?

你遇到的另一个问题是:

struct node *valid,*invalid; // Two pointers pointing to NULL

int main()
{
    // 1.
    // dynamically allocate memory for the `struct node` structure on the heap:

    valid = malloc(sizeof(struct node)); // no need to do a cast :(struct node *)
    invalid = malloc(sizeof(struct node)); // no need to do a cast :(struct node *)

    valid->top=-1;    // OK
    invalid->top=-1;  // OK
    //...

    // 2. OR use structures allocated on the stack:
    struct node valid_node;
    struct node invalid_node;

    valid = &valid_node;        // initialize pointer to the structure
    invalid = &invalid_node;    // initialize pointer to the structure 

   //....
}
声明int int size, score[size]; //variables for array purposes scanf ("%d", &size);

时,

size应该有一个有效值

将代码更改为:

score[size];

编辑,回答评论问题:

未初始化的局部变量在运行时获得未定义的值。在本地定义int size; //.. scanf ("%d", &size); int score[size]; //variables for array purposes 时,它们将在堆栈中分配。 *valid,*invalid也被放在堆栈上,但现在在不同的地方!由于size未初始化,因此它包含堆栈中该位置的任何内容。它可能是偶然的合理值,size或负值。在你的情况下,随机值是不好的,程序将崩溃。这称为UB(未定义行为)。全局定义0并不能解决问题。这只是运气。必须将*valid, *invalid初始化为正确的值,以确保正确的程序行为。