简体   繁体   English

为什么atoi无法正确转换为整数?

[英]Why is atoi not converting to integer properly?

I have a pseudoheader in a string, the first 12 bits are the file size, the next 4 are the buffer size, and the last 12 are an offset. 我在字符串中有一个伪头,前12位是文件大小,后4位是缓冲区大小,后12位是偏移量。 I want to store each one of this in a variable, I could get the string values, but atoi is not working properly when converting those to integers The program looks like this: 我想将其中的每个存储在一个变量中,我可以获取字符串值,但是当将它们转换为整数时, atoi无法正常工作。程序如下所示:

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

void readheader(char header[29], int filesize, int buffersize, int offset) {
  char fsize[13], bsize[5], oset[13];
  memcpy(fsize, &header[0], 12);
  fsize[12] = '\0';
  memcpy(bsize, &header[12], 4);
  bsize[4] = '\0';
  memcpy(oset, &header[16], 12);
  oset[12] = '\0';
  printf("String Values: filesize: %s, buffersize: %s, offset: %s\n", fsize, bsize, os$
  filesize = atoi(fsize);
  buffersize = atoi(bsize);
  offset = atoi(oset);
}

void main() {
  char test[] = "0000000051422048000000004096";
  int a, b, c;
  readheader(test, a, b, c);
  printf("Integer values: filesize: %d, buffersize: %d, offset: %d\n", a, b, c);
}

And the output looks like this: 输出看起来像这样:

String Values: filesize: 000000005142, buffersize: 2048, offset: 000000004096
Integer values: filesize: 0, buffersize: -1036019427, offset: 22039

Arguments in c are passed by value, if you want to modify a variable passed to a function, you need to pass it's memory location instead, then you can modify it c中的参数按值传递,如果要修改传递给函数的变量,则需要传递其内存位置,然后可以对其进行修改

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

/* Using int pointer type instead of int */
void readheader(char header[29], int* filesize, int* buffersize, int* offset) {
  char fsize[13], bsize[5], oset[13];
  memcpy(fsize, &header[0], 12);
  fsize[12] = '\0'; 
  memcpy(bsize, &header[12], 4);
  bsize[4] = '\0';  
  memcpy(oset, &header[16], 12);
  oset[12] = '\0';  
  printf("String Values: filesize: %s, buffersize: %s, offset: %s\n", fsize, bsize, oset);
  /* Dereferencing the pointers */
  *filesize = atoi(fsize); 
  *buffersize = atoi(bsize);
  *offset = atoi(oset);
}

void main() {
  char test[] = "0000000051422048000000004096";   
  int a, b, c;
  /* Passing by reference */
  readheader(test, &a, &b, &c);
  printf("Integer values: filesize: %d, buffersize: %d, offset: %d\n", a, b, c);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM