c - malloc函数返回的内存不保存数据

标签 c

在下面的代码中,我不明白为什么 win[] 没有获取值。我已经对下面代码中我感到困惑的行进行了评论。 请帮助我。 我是否犯了任何概念性错误?

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

void winner(int *speed,int *distance,int rats){
    float winner=(float)distance[0]/speed[0];
    float time;
    float *win=malloc(rats * sizeof(float));
    memset(win,0,rats*sizeof(float));
    for(int i=0;i<rats;i++) {
        time=(float)distance[i]/speed[i];
        if(time<=winner) {
            win[i]=time;   /*Problem is here*/ 
        }
    }
    for(int i=0;i<rats;i++) {
        if(win[i]!=0) {
            printf("%d\n",i+1);
        }
    }
    free(win);
}

int main() {
    int rats;
    int *speed,*distance;
    scanf("%d",&rats);
    speed=malloc(rats * sizeof(int));
    distance=malloc(rats * sizeof(int));
    for(int i=0;i<rats;i++) {
        scanf("%d",&speed[i]);
    }
    for(int i=0;i<rats;i++) {
        scanf("%d",&distance[i]);
    }
    winner(speed,distance,rats);
    free(speed);
    free(distance);
    return 0;

}

最佳答案

您的代码中至少存在 3 个问题:

  • 如果其中一只老鼠的时间短于第一只老鼠,您不会更改获胜者
  • 您没有为非获胜者初始化win[i]
  • 您没有利用最佳时间展示获胜老鼠

所以代替:

    if(time<=winner){
       win[i]=time;   /*Problem is here*/
     }

你应该有:

    win[i]=time; // always initialize !
    if(time<=winner){
       winner = time; // keep best time
    }

然后代替

for(int i=0;i<rats;i++){
  if(win[i]!=0){
      printf("%d\n",i+1);
     }
 }

你应该有:

for(int i=0;i<rats;i++){
  if(win[i] == time){ // display all rats having best time
      printf("%d\n",i+1);
     }
 }

关于c - malloc函数返回的内存不保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30097127/

相关文章:

c - g_object_new : assert from a call of g_application_send_notification()

c - 在STM32F3上用DMA生成正弦波-乱码输出

c - 在 Perl 程序中嵌入模块

c - GMP 库的整数乘法限制

c - 为什么 main 函数和 func 函数的 char 指针 p 的输出不同?

c - Posix evtsuspend 等效项

c - 向我的简单 shell 添加历史功能

c - 是否可以通过 C 变量而不是使用 GPIO_Pin_N 值读取和/或写入端口?

c - 如何更改此代码才能解决此挑战?

c - 原始套接字中的 TCP 数据包 - Centos 6.6