c - 动态字符数组 C 中的随机字符

标签 c arrays random chars

我需要有关 char 数组的帮助。我想创建一个 n-lenght 数组并初始化它的值,但是在 malloc() 函数之后数组比 n*sizeof(char) 长,并且数组的内容不仅仅是我分配的字符......在数组中很少随机字符,我不知道如何解决...我需要那部分代码用于学校考试的一个项目,我必须在星期天之前完成...请帮忙:P

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

int main(){

    char *text;

    int n = 10;

    int i;

    if((text = (char*) malloc((n)*sizeof(char))) == NULL){
        fprintf(stderr, "allocation error");
    }

    for(i = 0; i < n; i++){
        //text[i] = 'A';
        strcat(text,"A");
    }

    int test = strlen(text);
    printf("\n%d\n", test);

    puts(text);
    free(text);

    return 0;
}

最佳答案

在使用 strcat 之前先做

text[0]=0;

strcat 也期望第一个参数为空终止 char 数组。

来自 standard 7.24.3.1

  #include <string.h>
          char *strcat(char * restrict s1,
               const char * restrict s2);

The strcat function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1.

如果你不这样做,你认为 strcat 会如何知道第一个字符串的结束位置 将 \0 放入 s1

另外不要忘记为 \0 字符分配一个额外的字节。否则你写的是你分配的内容。这又是未定义的行为。

之前你有未定义的行为。

注意:

  • 您应该检查 malloc 的返回值以了解 malloc 调用是否成功。

  • 不需要转换malloc 的返回值。在这种情况下,从 void* 到相关指针的转换是隐式完成的。

  • strlen 返回 size_t 而不是 intprintf("%zu",strlen(文本))

关于c - 动态字符数组 C 中的随机字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48219002/

相关文章:

c - 如何在 opengl 中正确地构造四边形

c - While循环变量初始化和变量类型(C)

java - 通过迭代将字符串数组添加到二维字符串数组

actionscript-3 - 如何循环遍历帧号,如果为真则忽略该帧号?

c# - 如何根据百分比进行随机选择

创建一个充满随机唯一数字的数组

c - 在静态库中定义枚举

c - 使用 ffi 在 ruby​​ 中添加共享库

javascript - 如何将数组的 Javascript 数组转换为 JSON 字符串

php - 插入数组并在 PhpMyAdmin 中显示值