试图将一些数字放入char数组中

时间:2012-08-23 11:24:12

标签: c

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

1 个答案:

答案 0 :(得分:2)

你有很多问题:

  1. 结果字符串不是以零结尾。添加some_string[i] = '\0';以解决此问题
  2. 字符(char)类似于&#34;字母&#34;,但random % 10产生一个数字(int),当转换为字符时会产生控制代码( ASCII字符0-9是控制代码)。您最好使用some_string[i] = (random % 10) + '0';
  3. 你使用固定长度的字符串(20个字符),这可能就足够了,但它可能会导致许多问题。如果您是初学者并且没有学习动态内存分配,那么现在还可以。但请记住,固定长度的缓冲区是有缺陷的C代码的十大原因之一。如果你必须使用固定长度的缓冲区(有正当理由这样做),ALLWAYS检查你是否没有超越缓冲区。使用预定义常量作为缓冲区长度。
  4. 除非您的练习的重点是尝试将数字转换为字符串,否则请使用像snprintf这样的libc函数将任何内容打印到字符串中。
  5. 不要使用全局变量(some_string),如果你这样做(对于一个小例子来说还可以),那么返回这个值是没有意义的。
  6. 稍微好一点的版本:

    #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;
    }