如何从整数数组中减去 1

How do I subtract 1 from an array of integers

我在学校学习C,我的项目有点困难。 基本上,我正在编写一个函数来获取包含正整数的字符串。该函数从该整数中减去 1,并将获得的值放入字符串中。

所以,如果我有这个;

char nums[] = "2462";

如何编写一个从整数中减去 1 的函数,以便结果为“2461”??

一种方法是转换字符串 -> 整数 -> 字符串。

您可以使用 atoi and sprintf 来完成此操作。

实施简单(远非完美):

#include <stdlib.h>
#include <stdio.h>
int main() 
{
  int a;
  char b[5];
  a = atoi("2462");
  a--;
  sprintf(b, "%d", a);
  printf("%s\n", b);
  return 1;
}

首先,将字符数组转换为整数。

您可以使用 atoi(ASCII 到整数),但是因为它 returns 0 错误所以无法区分成功转换 "0" 和错误之间的区别。

而是使用 strtol(STRing TO Long integer)。

// end stores where parsing stopped.
char *end;

// Convert nums as a base 10 integer.
// Store where the parsing stopped in end.
long as_long = strtol(nums, &end, 10);

// If parsing failed, end will point to the start of the string.
if (nums == end) {
  perror("Parsing nums failed");
}

现在可以减法了,用sprintf把整数变回字符串,然后放到nums中。

sprintf(nums, "%ld", as_long - 1);

这并不完全安全。考虑 nums 是否为 "0"。它只有space的1个字节。如果我们减去 1 那么我们有 "-1" 并且我们正在存储 2 个字符,而我们只有 1.

的内存

有关如何安全执行此操作的完整说明,请参阅 How to convert an int to string in C?

或者,不存储它,只打印它。

printf("%ld", as_long - 1);