gpt4 book ai didi

C动态分配的数组使用memset进行初始化

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:31 24 4
gpt4 key购买 nike

所以我编写了一个关于动态分配的 char 数组的程序,该程序尚未完成,但我在运行该程序后得到了一些不同的返回值,没有警告,编译器中没有错误,所以我不不知道为什么我有时也会收到这个程序崩溃..

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(){
int n,i;
char *tab=NULL;
printf("New size of array: ");
scanf("%d",&n);
tab=(char*)malloc(n*sizeof(char));
memset(tab,'X',n*sizeof(tab));
for(i=0;i<n;i++)
printf("%c",tab[i]);
free(tab);
return 0;
}

最佳答案

在你的 memset 中你写了 n * sizeof(tab),我想你想写: n * sizeof(字符)

为了安全起见,您还可以在 malloc 的末尾添加 +1 并检查返回值。

关于C动态分配的数组使用memset进行初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34844883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com