2

我正在尝试创建一个由一些字母和数字组成的 char 数组(该函数最初要复杂得多,但我一直在简化它以找出它为什么不能正常工作)。所以我有一个 char 数组,我在其中放置了 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;
}
4

1 回答 1

2

你有很多问题:

  1. 结果字符串不是以零结尾的。添加some_string[i] = '\0';以解决此问题
  2. 字符 ( char) 类似于“字母”,但random % 10会产生一个数字 ( int),当转换为字符时会产生控制代码(ASCII 字符 0-9 是控制代码)。你最好用some_string[i] = (random % 10) + '0';
  3. 您使用的是固定长度的字符串(20 个字符),这可能就足够了,但可能会导致很多问题。如果您是初学者并且还没有学习动态内存分配,那么现在就可以了。但请记住,固定长度的缓冲区是 C 代码出现错误的 10 大原因之一。如果您必须使用固定长度的缓冲区(这样做有正当理由),请始终检查您是否没有超出缓冲区。使用预定义的常量作为缓冲区长度。
  4. 除非您练习的全部目的是尝试将数字转换为字符串,否则请使用 libc 函数,例如snprintf将任何内容打印到字符串中。
  5. 不要使用全局变量 ( 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;
}
于 2012-08-23T11:49:49.827 回答