【问题标题】:random chars in dynamic char array C动态字符数组C中的随机字符
【发布时间】:2018-01-12 03:08:52
【问题描述】:

我需要关于 char 数组的帮助。我想创建一个 n 长度数组并初始化它的值,但是在 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;
}

【问题讨论】:

标签: c arrays random chars


【解决方案1】:

在使用strcat之前做好

text[0]=0;

strcat 期望空终止的char 数组也用于第一个参数。

来自standard 7.24.3.1

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

strcat 函数附加 s2 指向的字符串的副本 (包括终止空字符)到字符串的末尾 由 s1 指向。 s2 的初始字符覆盖 null s1 末尾的字符。

如果你不知道strcat 会如何知道第一个字符串的结尾? 在s1 中添加\0

不要忘记为\0 字符分配一个额外的字节。否则,您正在写超出您分配的内容。这又是未定义的行为。

之前你有未定义的行为。

注意:

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

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

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

【讨论】:

    【解决方案2】:

    首先,您可以在

    中使用malloc
    text = (char*) malloc((n)*sizeof(char)
    

    并不理想。您可以将其更改为

    text = malloc(n * sizeof *text); // Don't cast and using *text is straighforward and easy. 
    

    所以声明可以是

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

    但实际问题出在

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

    strcat 文档说

    dest - 这是指向目标数组的指针,它应该包含 一个 C 字符串,并且应该足够大以包含连接的 结果字符串。

    只是指出上面的方法是有缺陷的,你只需要考虑C字符串"A"实际上包含两个字符,A和终止\0(空字符)。在这种情况下,当in-2 时,您有越界访问或缓冲区溢出1。如果你想用 A 填充整个 text 数组,你可以这样做

    for(i = 0; i < n; i++){ 
        // Note for n length, you can store n-1 chars plus terminating null
        text[i]=(n-2)==i?'A':'\0'; // n-2 because, the count starts from zero
    }
    //Then print the null terminated string
    printf("Filled string : %s\n",text); // You're all good :-)
    

    注意:使用 valgrind 之类的工具来查找内存泄漏和超出范围的内存访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多