gpt4 book ai didi

c - 解析后奇怪的输出

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:24 25 4
gpt4 key购买 nike

我现在有一些奇怪的错误,当扫描一个更大的文件时,比如这个:

  1. 0x1001 0x0001
  2. 0x1001 0x0002
  3. 0x0004
  4. 0x0005
  5. 0x0005
  6. 0x0005
  7. 0x0005
  8. 0x0007 0x0001

我正在使用这段代码:

 int *inst = (int*)malloc(sizeof(int));
int *op1 = (int*)malloc(sizeof(int));

FILE *fp = fopen(argv[1], "r");
char line [32]; // Max line size
int count=0;

while(fgets (line, sizeof(line),fp) != NULL){
sscanf(line, "%x" "%x", &inst[count], &op1[count]);
printf("0x%x 0x%x\n", inst[count],op1[count]);
count++; }

输出一开始很好,但从第 7 行开始变得奇怪:

  1. 0x1001 0x1
  2. 0x1001 0x3
  3. 0x4 0x0
  4. 0x5 0x0
  5. 0x5 0x0
  6. 0x5 0x0
  7. 0x5 0x241
  8. 0x1007 0x0

从那时起,如果我添加更多行来解析所有内容,它会变得越来越奇怪。我是不是越界了?

最佳答案

问题数量

  1. 大:不分配内存。

  2. 不使用sscanf()

    的结果
  3. 不以文本模式打开文件

建议:

// Instead of 8, make 2 passes to find the number of lines or reallocate as you go.
int *inst = calloc(8, sizeof(*inst)); /
// calloc initializes to 0, nice as your various lines don't always have 2 numbers.
int *op1 = calloc(8, sizeof(*op1));
FILE *fp = fopen(argv[1], "rt");
...
int result = sscanf(line, "%x" "%x", &inst[count], &op1[count]);
switch (result) {
case 1: printf("0x%x\n", inst[count]); break;
case 2: printf("0x%x 0x%x\n", inst[count],op1[count]); break;
default: ; // handle error
}

关于c - 解析后奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19055580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com