简体   繁体   English

在C中保存数组中的数据

[英]saving data from an array in C

I should mention that I am in my 1st 2 weeks of an intro to programming class before people get too crazy with answers. 我应该提一下,在人们对答案过于疯狂之前,我是在编程课程的前2周内。

Using this array as an example, 以此数组为例,

int scores[30] = {90,85,100,50,50,85,60,70,55,55,80,95,70,60,95,
  80,100,75,70,95,90,90,70,95,50,65,85,95,100,65}

I am trying to parse through it to create 2 new parallel arrays to use later. 我正在尝试解析它以创建2个新的并行数组以供稍后使用。 The idea is to make one array that holds the "scores" and one that holds the "occurrences" of each score. 我们的想法是制作一个包含“得分”的数组和一个包含每个得分“出现次数”的数组。 I end up compiling with no errors however during run time it crashes. 我最终编译没有错误,但在运行时崩溃。

void frequency(int scores[], int max){
    int i, x=0, temp=0, count=0, sum=0, mode=0;
    int score[sum]; //unknown length of array, sum gets added after the while loop
    int freq[sum];
    printf("score\tfrequency\n");
    printf("-----\t---------\n");
    fprintf(fp, "score\tfrequency\n");
    fprintf(fp, "-----\t---------\n");
    for (i = 0; i < max; ++i){
        while (scores[i]==scores[x]){ 
            x++; 
            count++;
            sum++;
            temp = x-1;
            if(scores[i] != scores[x]){
                //printf("   %d\t      %d\n",scores[i], count);
                freq[i] = count;
                score[i] = scores[i];
                count=0;

                i=temp;
                x=temp+1;
                sum++;
                printf("%d\t%d", score[i], freq[i]);
                fprintf(fp, "%d\t%d", score[i], freq[i]);
            }
        }
    }
}

This part: 这部分:

int i, x=0, temp=0, count=0, sum=0, mode=0;
int score[sum];
int freq[sum];

looks wrong. 看起来不对劲

You set sum to zero and then use it for the array dimension. 您将sum设置为零,然后将其用于数组维度。 Did you mean to do: 你的意思是:

sum = max;

I end up compiling with no errors however during run time it crashes. 我最终编译没有错误,但在运行时崩溃。

Reason : 原因

The reason why your program crashes is because you have not allocated sufficient memory to the arrays that you use int the frequency() function 程序崩溃的原因是你没有为你在frequency()函数中使用的数组分配足够的内存

void frequency(int scores[], int max){
int i, x=0, temp=0, count=0, sum=0, mode=0;
int score[sum];
int freq[sum];

Solution: 解:

So, is there a way to provide memory during run time according to requirements or change memory size of blocks during compile time? 那么,有没有办法在运行时根据需求提供内存或在编译期间更改块的内存大小?

Yes, that's the very reason why Dynamic memory allocation is used.... though you send a fixed array to the frequency() function in your code, the function I've provided works for any integer array you send.. 是的,这就是使用动态内存分配的原因....虽然您在代码中向frequency()函数发送了一个固定数组,但我提供的函数适用于您发送的任何整数数组。


Here I've provided code in which 在这里,我提供了代码

  • one array stores all the unique scores 一个数组存储所有唯一的分数

  • and other array stores number of occurrences of each score 和其他数组存储每个得分的出现次数

I've done this using dynamic memory allocation.. I think it's easy to understand if you have basic understanding of dynamic memory allocation functions.. if you have any doubts, ask me through the comments :) and by the way I've assumed your main function to be : 我已经使用动态内存分配完成了这个。我认为如果你对动态内存分配函数有基本的了解就很容易理解..如果你有任何疑问,请通过评论:)和我假设的方式你的主要功能是:

int main()
{
    int scores[30] = {90,85,100,50,50,85,60,70,55,55,80,95,70,60,95,
      80,100,75,70,95,90,90,70,95,50,65,85,95,100,65};
    frequency(scores,30);
    return 0;
}

Code: 码:

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

void frequency(int scores[], int max);

int main()
{
    int scores[30] = {90,85,100,50,50,85,60,70,55,55,80,95,70,60,95,
      80,100,75,70,95,90,90,70,95,50,65,85,95,100,65};
    frequency(scores,30);
    return 0;
}

void frequency(int scores[], int max)
{
    int i,j,count=0,flag=0,occur=0;
    int *score=malloc(sizeof(int)); 
    if(malloc==NULL)
    {
         printf("memory allocation failed");
         exit(1);
//it's good to check if memory allocated was successful or not
//I've avoided it for further allocations,to decrease the size of post :)
    }
    int *freq=malloc(sizeof(int));
    printf("score\tfrequency\n");
    printf("-----\t---------\n");


    //building array which has only scores
    for(i=0;i<max;i++)
    {
        if(count==0) //first time
        {
            score=realloc(score,(count+1)*sizeof(int)); 
            //increasing size of array by 1*sizeof(int)
            score[count]=scores[i];
            count++;
        }//first one requires no checking whether it's repeated or not
        else
        {
            flag=0; //resetting flag value
            for(j=0;j<count;j++)
            {
                if(scores[i]==score[j])
                {
                    flag=1; //
                    break;
                }
            }

            if(flag==0) // if not repeated need to add new element
            {
                score=realloc(score,(count+1)*sizeof(int));
                score[count]=scores[i];
                count++;
            }

        }
    }

    //allocating memory for frequency array
    freq=realloc(freq,count*sizeof(int));

    //building array which has frequency of each score
    for(i=0;i<count;i++)
    {
        occur=0;
        for(j=0;j<max;j++)
        {
            if(score[i]==scores[j])
                occur++;
        }
        freq[i]=occur;
    }

    for(i=0;i<count;i++) //printing output
        printf("\n  %d\t  %d\n",score[i],freq[i]);

    free(score); //freeing the blocks 
    free(freq);
}

My approach is quite simple to understand 我的方法很容易理解

  1. first I create array score which creates extra memory whenever it encounters unique elements and stores in it 首先,我创建数组score ,只要遇到独特的元素和存储,就会创建额外的内存
  2. and then I check occurrences for each of the element of score array in the scores array and store them in freq array. 然后我检查score数组中scores数组的每个元素的出现次数并将它们存储在freq数组中。

Output: 输出:

score   frequency
-----   ---------

  90      3

  85      3

  100     3

  50      3

  60      2

  70      4

  55      2

  80      2

  95      5

  75      1

  65      2

I hope this is what you were trying to achieve :) 我希望这是你想要实现的目标:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM