【问题标题】:Array histogram main数组直方图主
【发布时间】:2014-02-03 19:19:27
【问题描述】:

我正在开发这个非常简单的 C 程序,它从数组构建直方图。它特别做的是在第二个数组上写入第一个数组的密码,然后是它们的出现次数。例如:如果数组 A 是 {2,3,2,5,6,6,6},则 A 的数组直方图将为 {2,2,3,1,5,1,6,3}。好的,所以我的程序编译得很好,没有任何警告或错误。但是在我插入数组 A 的值后程序停止工作。我在哪里失败了???谢谢!!

typedef unsigned short int boolean;
#define TRUE 1
#define FALSE 0
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <conio.h>

boolean Array_Histogram(int *A, int N, int **H, int *count){
  int i,j;
  boolean found;
  *H = (int *) malloc( sizeof(int)*2*N );
  if(*H==NULL)
    return FALSE;
  (*count)=0;
  for(i=0;i<N;i++){
    found=FALSE;
    j=0;
    while(found==FALSE && j<(*count)*2){
      if(A[i]==(*H[j]))
        found=TRUE;
      else j+=2;
    }
    if(found==TRUE){
      (*H)[j+1]++;
    }
    else{
      (*H)[j] = A[i];
      (*H)[j+1] = 1;
      (*count) ++;

    }
  }
  return TRUE;
}


int main(){

  int N;
  int count;
  int *A;
  int **H;
  int *i;

  i=0;
  printf("Inserisci N, dimensione dell'array A:");
  scanf("%d", &N);
  if(N<=0){

    return 0;
  }
  A= (int*) malloc (sizeof(int)*N);
  *H = (int *) malloc( sizeof(int)*2*N );
  for(count=0;count<N;count++){
    printf("\n Inserisci il valore %d di A:", count);
    scanf("%d", &A[count]);
  }
  Array_Histogram(A,N,H,i);
  printf("\nI valori dell'istogramma sono:");
  for(count=0;count<2*N;count++)
    printf("\n %d", (*H)[count]);
  return 0;
}

【问题讨论】:

  • 请正确INDENT您的代码。我不会按原样阅读它。还有..boolean?! 如果你真的想定义这样一个类型(为什么?),使用bool,就像除了java之外的几乎所有语言一样。
  • typedef unsigned short int boolean;很搞笑:D
  • 布尔变量;然后比较 TRUE 和 FALSE grusel。 "if (found)" 或 "if (!found)" 可读性更强
  • 抱歉,我无法缩进我的代码。显然这太难了._。然而问题就来了。调试。正如你可能理解的那样,我不是一个专家级的程序员,也没有人真正教过我如何调试。我正在使用eclipse,但是断点似乎有问题..它们没有按我预期的那样工作。在变量列表中,在 H 处,有以下消息:无法执行 MI 命令:-data-evaluate-expression *(*(H)) 来自调试器后端的错误消息:无法访问地址 0x404008a1 处的内存。我真的无法在互联网上找到这意味着什么。你能帮我吗??
  • 谁教这些丑陋的“大写单字母”变量名?!?

标签: c arrays histogram


【解决方案1】:

main 中的变量 H 类型错误。应该声明:

int *H;

为此,您需要在 main 中再更改 2 行:

H = malloc( sizeof(int)*2*N );

Array_Histogram(A,N,&H,i);

另外,你只需要分配一次 H。

【讨论】:

  • 另外,&amp;H 应该传递给ArrayHistogram
  • @Magnus 我添加了需要更新的两行。
【解决方案2】:

我不太确定你想达到什么目的,但你的问题是取消引用 null 指针。

H 是指向整数的双指针。所以你必须在使用*H之前使用mallocH分配内存

int **H;
*H = malloc( sizeof(int)*2*N );

编辑:

建议你阅读一些关于指针here的基础知识

【讨论】:

  • 请不要强制转换 malloc() 的结果;
【解决方案3】:
  1. 您为 H 分配了两次内存(一次在 main 中,一次在 func 中)。
  2. H 被声明为 int **,内存被分配给每个整数指针的 2*N 个元素,这可能不是您想要做的。 如果您只想输出为 {2,2, 3,1..},那么您可能只需要一个 int *H;

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 2015-02-10
    • 2018-10-03
    • 2014-04-26
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多