我正在尝试创建一个由一些字母和数字组成的字符数组(该函数最初要复杂得多,但我不断简化它以找出它无法正常工作的原因)。所以我有一个字符数组,其中放置了 2 个字符,并尝试向其中添加一些数字。 由于我无法弄清楚的原因,这些数字没有添加到数组中。这可能真的很愚蠢,但我是 C 新手,所以这里是简化的代码。非常感谢任何帮助,谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char some_string[20];
char *make_str() {
some_string[0] = 'a';
some_string[1] = 'x';
int random = 0;
int rand_copy = 0;
random = (rand());
rand_copy = random;
int count = 2;
while ( rand_copy > 0 ) {
rand_copy = rand_copy / 10;
++count;
}
int i=2;
for (i=2; i<count; i++) {
some_string[i] = random%10;
random = random/10;
}
return (some_string);
}
int main(int argc, const char *argv[]) {
printf("the string is: %s\n",make_str());
return 0;
}
最佳答案
你有很多问题:
- 生成的字符串不是以零结尾的。添加
some_string[i] = '\0';
来修复此问题 - 字符 (
char
) 类似于“字母”,但random % 10
会生成一个数字 (int
),当转换为控制代码中的字符结果(ASCII 字符 0-9 是控制代码)。你最好使用some_string[i] = (random % 10) + '0';
- 您使用的是固定长度字符串(20 个字符),这可能足够了,但可能会导致许多问题。如果您是初学者并且还没有学习动态内存分配,那么现在没关系。但请记住,固定长度缓冲区是 C 代码有缺陷的十大原因之一。如果您必须使用固定长度的缓冲区(这样做有合理的理由),请务必检查您是否没有超出缓冲区。使用预定义的常量作为缓冲区长度。
- 除非您练习的重点是尝试将数字转换为字符串,否则请使用
snprintf
等 libc 函数将任何内容打印到字符串中。 - 不要使用全局变量 (
some_string
),如果使用(对于一个小示例来说没问题),则返回此值没有任何意义。
稍微好一点的版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_LENGTH 20
char some_string[BUF_LENGTH];
char *make_str() {
some_string[0] = 'a';
some_string[1] = 'x';
int random = rand();
int rand_copy = random;
int count = 2;
while (rand_copy > 0) {
rand_copy = rand_copy / 10;
++count;
}
int i;
for (i = 2; i < count; i++) {
/* check for buffer overflow. -1 is for terminating zero */
if (i >= BUF_LENGTH - 1) {
printf("error\n");
exit(EXIT_FAILURE);
}
some_string[i] = (random % 10) + '0';
random = random / 10;
}
/* zero-terminate the string */
some_string[i] = '\0';
return some_string;
}
int main(int argc, const char *argv[]) {
printf("the string is: %s\n",make_str());
return 0;
}
关于c - 尝试将一些数字放入 char 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12090489/