我如何将整数插入内存块?

问题描述 投票:0回答:2

有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如,将(int a = 10)转换为(char string [200])。

c memory
2个回答
0
投票

有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如,将[int a=10)转换为[char string[200])。

是,有使用printf的字符串版本>

snprinf(string,200,"%d",a);

如果您想手动执行上述操作,也可以使用div和mod乘以10的循环来生成字符串。 [有关此https://stackoverflow.com/a/49615617/391691的示例,请参见另一个答案

要从字符串sscanfatoiatol中获取整数,请返回>]

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

void main(){
   int a;
   char string[200];


   a = 10;
   snprintf(string,200,"%d",a);
   printf("As string:%s As int:%d\n",string,atoi(string));
}

对我来说,这个问题的解释仍然不清楚,与以前的答案相比,这代表了对该问题的另一种解释https://stackoverflow.com/a/58584291/391691]

有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如,将(int a = 10)转换为(char string [200])。

在此答案中,我将陈述最小的问题,该问题未提供以下任何内容的详细信息:

  • string中整数的表示/编码
  • 应在其上运行的体系结构
  • 插入整数的位置
  • 如果此问题与将整数转换为ASCII表示形式有关,则answer by @Simson是您所需要的。

    C允许您通过将char数组强制转换为int*来将整数[1]放入c样式字符串的任何位置。

// string: the array (char*)
// pos: position in the array (size_t)
// to_insert: the value to insert (int)
(*(int*)(&string[pos])) = to_insert;

但请注意:这是大锤方法。执行此操作时必须非常小心,否则您的代码可能会在不同平台上显示未定义的行为。例如,您必须手动检查并回答:

  • 内存对齐:我将尝试在体系结构无法寻址的位置插入整数吗?
  • Endianness:实际上是我想要的将该整数写入数组的方式吗?
  • sizeof(int)
  • :整数是否仍适合数组?也许考虑使用任何固定长度的整数类型,例如uint16_tuint32_t,...
  • 可能还有更多
  • 以下示例显示了所讨论方法的用法:

#include <stdio.h>

void insert_at_pos(char* arr, size_t pos, int to_insert){
  (*(int*)(&arr[pos])) = to_insert;
}

int main(void) {
  char string[200] = {0};
  insert_at_pos(string, 3, 10);

  //print char by char as hex
  for (size_t i=0; i < sizeof(string)/sizeof(*string); ++i){
    printf("%x ",(unsigned char)string[i]);
  }
}

运行示例:

$ ./main
0 0 0 a 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

[1]:通过“放置”,我可以原样理解。


-1
投票

有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如,将(int a = 10)转换为(char string [200])。

© www.soinside.com 2019 - 2024. All rights reserved.