查找数组

时间:2017-06-27 19:16:57

标签: c pointers random casting dynamic-allocation

我有一个数组,我必须找到它中最大的元素,告诉它有多少次以及在什么位置。我必须使用指针和动态内存分配。

当数组随机填充时不起作用,但在手动填充时工作正常。

此代码正常运行:

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

void max_elem (int n, float* vett) {

  int i=0, *pos, p=0, n_ele_pos;
  float max=*(vett);

  pos=(int*)malloc(sizeof(int));
  if (pos==NULL) {printf("BUM\n" ); exit (0);}
  *(pos)=0;
  for (i=1; i<n; i++) {
    if (*(vett+i)>max) {
      max=*(vett+i);
      p=0;
      *(pos)=i;
    }
    else  if (*(vett+i)==max) {
      p++;
      *(pos+p)=i;
    }
  }
  if (p==0) {
    printf("\nmax element is %f, in position %d  ", max, *pos+1);
  }
  else {
    printf("\n max element %f, %d times in position\n", max, p+1);
    for (i=0; i<p+1; i++) {
    printf("%d  ", *(pos+i)+1);
    }
  }
  printf("\n\n");
  free(pos);
}

int main()
{
    int i,n;
    float *element;
    printf("\n\n Pointer : Find the largest element using Dynamic Memory Allocation :\n");
    printf("-------------------------------------------------------------------------\n");
    printf(" Input total number of elements(1 to 100): ");
    scanf("%d",&n);
    element=(float*)calloc(n,sizeof(float));  // Memory is allocated for 'n' elements
    if(element==NULL)
    {
        printf(" No memory is allocated.");
        exit(0);
    }
    printf("\n");
    for(i=0;i<n;++i)
    {
       printf(" Number %d: ",i+1);
       scanf("%f",element+i);
    }

    max_elem (n, element);
    return 0;
}

但下一个没有。我必须用我决定的特定范围内的随机数填充数组,甚至从整数随机数的十进制到十进制极值(是的,我知道它实际上并没有多大意义)。填充十进制数时搜索有时候工作正常,整数我只有0。

这里是代码:

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

float rand_float (float *, float *);
int rand_int (float *, float *);
void min_max(float *, float *, float *, float *);
int num_intero(float);
void max_elem (int, float*);

int main () {

  int n, i, t;
  float x1, x2;

  printf ("array size:\t");
  scanf ("%d", &n);
  printf("\ninterval extremes:\t");
  scanf ("%f %f", &x1, &x2);
  do {
    printf("1 for decimal random numbers, 2 for integers:\t");
    scanf("%d", &t);
  } while (t!=1 && t!=2);
  srand(time(NULL));
  switch (t) {

    case 1 :  {

      float *vett;

      vett=(float*)calloc(n, sizeof(float));
      if (vett==NULL) {printf("BUM\n" ); exit (0);}
      for (i=0;i<n;i++) {
        *(vett+i)=rand_float(&x1, &x2);
        printf("%d__\t%10f\n", i, *(vett+i));
      }
      max_elem (n, vett);
      free(vett);

      break;
    }
    case 2 :  {

      int *vett;

      vett=(int*)calloc(n, sizeof(int));
      if (vett==NULL) {printf("BUM\n" ); exit (0);}
      for (i=0; i<n; i++) {
        *(vett+i)=rand_int(&x1, &x2);
        printf("%d__\t%10d\n", i, *(vett+i));
      }
      max_elem (n, (float*)vett);
      free (vett);

      break;
    }
  }

  return 0;
}

void min_max (float*x1, float *x2, float *min, float *max) {

  if (*x1<*x2) {
    *min=*x1;
    *max=*x2;
  }
  else {
    *min=*x2;
    *max=*x1;
  }
}

float rand_float (float *x1, float *x2) {

  float min, max;

  min_max(x1, x2, &min, &max);
  return ((max-min)*(float)rand()/RAND_MAX)+min;
}

int num_intero (float min) {

  if (min/(int)min==1)
    return 1; //e' intero
  else return 0;
}

int rand_int (float *x1, float *x2) {

  float min, max;

  min_max(x1, x2, &min, &max);
  if ((int)min==(int)max) {
    return (int)min;
  }
  else  if (min==0) {
          return (rand()%((int)(max)+1));
        }
        else  if (max==0) {
                return (rand()%((int)(-min)+1)+min);  //funziona anche con ((int)(min)-1)+min
              }
              else if ((int)min!=(int)max) {
                      if (num_intero (min)==1) {
                        return (rand()%((int)(max-min)+1)+min);
                      }
                      else  if (num_intero (max)==0) {
                              return (rand()%((int)(max-min))+min+1);
                            }
                            else return (rand()%((int)(max-min)+1)+min+1);
              }
}

void max_elem (int n, float* vett) {

  int i=0, *pos, p=0, n_ele_pos;
  float max=*(vett);

  pos=(int*)malloc(sizeof(int));
  if (pos==NULL) {printf("BUM\n" ); exit (0);}
  *(pos)=0;
  for (i=1; i<n; i++) {
    if (*(vett+i)>max) {
      max=*(vett+i);
      p=0;
      *(pos)=i;
    }
    else  if (*(vett+i)==max) {
      p++;
      *(pos+p)=i;
    }
  }
  if (p==0) {
    printf("\nmax element is %f, in position %d  ", max, *pos+1);
  }
  else {
    printf("\n max element %f, %d times in position\n", max, p+1);
    for (i=0; i<p+1; i++) {
    printf("%d  ", *(pos+i)+1);
    }
  }
  printf("\n\n");
  free(pos);
}

另外,当数组很大的时候我有这样的运行时错误,我没有第一个代码: error

实施例: first code, second code and integers error(bottom)

我使用gcc和atom编辑器在Ubuntu 16.04(gnome)上。 谢谢,抱歉。

1 个答案:

答案 0 :(得分:1)

让我们稍微简化一下。

  

我有一个数组,我必须找到它中最大的元素,告诉它有多少次以及在什么位置。我必须使用指针和动态内存分配。

因此,在最糟糕的情况下,当您的数组包含相同的元素时,您将拥有与元素相同数量的位置。如果您不需要优化代码到内存使用,那么您可以分配两个长度相同的数组(一个用于数字,一个用于位置)。

下一个简化选项是在填充数组时找到最大值。 (无论fillig方法使用随机数量的读取用户输入,您都可以确定在将数据逐个插入数组时的最大值。)

也许你可以找到更多的简化选项,但有了这些选项,你可以放弃max_elem功能:

#include <stdio.h>
#include <stdlib.h>
#include <float.h> /* for FLT_MIN */

void assert_alloc(void* ptr) {
    if(ptr == NULL) {
        printf("No memory is allocated.\n");
        exit(0);
    }
}

int main() {
    int i, n, k = 0, *positions;
    float max = FLT_MIN, *elements; /* max is now the smallest possible float */

    printf("Input total number of elements(1 to 100): ");
    scanf("%d", &n);

    /* allocate array of same size for numbers and for positions */
    elements = (float*)calloc(n, sizeof(float));
    assert_alloc(elements);

    positions = (int*)calloc(n, sizeof(int));
    assert_alloc(positions);

    /* fill the array and find the maximum meanwhile */
    for(i = 0; i < n; ++i) {
        printf("Number %d: ", i + 1);
        scanf("%f", elements + i);

        if(max < *(elements + i))
            max = *(elements + i);
    }
    printf("\nmax element is %f, ", max); /* max is already known */

    /* find the positions of the maximal number */
    for(i = 0; i < n; ++i) {
        if(max == *(elements + i)) {
            *(positions + k) = i;
            k++;
        }
    }

    /* print the positions of the maximal number */
    if(k > 1) {
        printf("%d times in position\n", k);
        for(i = 0; i < k; i++)
            printf("%d  ", *(positions + i) + 1);
    }
    else {
        printf("in position %d", *positions + 1);
    }    
    printf("\n");

    free(elements);
    free(positions);
    return 0;
}

我检查了你的代码,它有两个问题。主要问题出在max_elem函数中,您必须使用calloc或将sizeof(int)乘以n

pos = (int*)malloc(n * sizeof(int));

执行此操作后,您的第二个示例将适用于float类型。它不适用于int类型的原因是您的max_elem仅接受float个指针。您将int指针作为max_elem(n, (float*)vett);传递给intpointer arithmetics导致错误,并且因为floatvett以不同方式表示在内存中。要解决此问题,请将float*指针声明为int,无论您是否使用float<div class="gallery-background-colour"> <section class="wrp"> <span id="gallery-main" class="gallery"></span> <div class="container-fluid vertical-center"> <div class="row"> <div class="col-sm-12"> <h2>GALLERY</h2> <p class="larger-font">We create everlasting memories.</p> </div> </div> </div> </section> </div> 值填充它。

Live Demo

相关问题