我需要有关 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
数组。
#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
而不是int
。printf("%zu",strlen(文本))
关于c - 动态字符数组 C 中的随机字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48219002/