【问题标题】:fill data in an array with zeros用零填充数组中的数据
【发布时间】:2013-06-20 07:05:18
【问题描述】:

我已经编写了这部分代码,它打开一个 txt 文件来写入 strtok 每 10 秒从缓冲区给我的结果(令牌)。此缓冲区从串行设备读取。

while(fgets(buff, sizeof(buff), fp) != NULL)
 {
    fputs(buff,stdout);
    FILE *ft = fopen("/home/pi/Desktop/data.txt","a+");
    struct tm *tp;
    time_t t;
    char s[80];
    t = time(NULL);
    tp = localtime(&t);
    strftime(s, 80, "%d/%m/%Y  %H:%M:%S", tp);
    char *pos = strchr(buff,'N');
    if (pos)
    {
         ptr = strtok(buff, "Nodo_,=:V()");
         i = 0;
       while (ptr != NULL)
         {
          if (i == 0)
             strcat(number, ptr); 
          if (i == 2)
             strcat(temp, ptr); 
          if (i == 4)
             strcat(hr, ptr); 
          if (i == 6)
             strcat(dw, ptr); 
          if (i == 8)
             strcat(vcc, ptr); 
          ptr = strtok(NULL, "Nodo_,=:V()");
          i++;
         }
      printf("Results: %s, %s, %s, %s, %s\n", number, temp, hr, dw, vcc);
char (*table1[1][5])[6] = {{&number, &temp, &hr, &dw, &vcc}};
       for(int i = 0; i<1; i++)
       {
          fprintf(ft,"%s ",s);
          for(int j = 0; j<5; j++)
          fprintf(ft,"%s ",table1[i][j]);
       }
      fprintf(ft,"\n");
      buff[sizeof(buff)-1] = '\0';
      memset(nodo, 0, sizeof(number));
      memset(temp, 0, sizeof(temp));
      memset(hr, 0, sizeof(hr));
      memset(dw, 0, sizeof(dw));
      memset(vcc, 0, sizeof(vcc));
      printf("\n");

     }
fclose(ft);
  }
close_port(fd);

我的txt中有这样的结果

19/06/2013  13:16:34 7 20.83 51.79 11.05 4.85 
19/06/2013  13:16:34 10 21.83 53.79 12.05 3.85

从结果中可以看出,每个数字 7 或 10 返回 4 个数字。我想创建以下内容: 如果数字=7 那么

20.83 51.79 11.05 4.85 0 0 0 0 

如果数字=7 则

 0 0 0 0 21.83 53.79 12.05 3.85

我的意思是我想要一个零数组。然后如果 number=7 将值放在位置 0-3 中,则清理数组,如果 number=10 则将值放在位置 4-7 中。有什么好主意吗?

【问题讨论】:

  • 问题不清楚。如果设置为零的数组是问题,那么您可以使用memset 函数。
  • 不,我知道使用 memset 我可以设置一个带零的数组,我的问题是如何使用我描述的位置进行上述实现
  • 是的,现在我看到您在代码中使用了memset。也许您可以使用memcpy?我的意思是在一个数组中收集四个数字,然后使用 memcpy 将它们复制到从所需位置开始的零数组。

标签: c arrays


【解决方案1】:

也许你应该使用 calloc... 看看这个 http://www.codingunit.com/c-reference-stdlib-h-function-calloc

【讨论】:

    猜你喜欢
    • 2017-10-24
    • 2021-03-24
    • 2020-03-21
    • 2016-11-06
    • 2021-11-25
    • 2018-10-05
    • 2018-11-30
    • 1970-01-01
    • 2013-12-13
    相关资源
    最近更新 更多