gpt4 book ai didi

c - 使用 malloc 分配动态内存

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:52 25 4
gpt4 key购买 nike

这是我的代码示例。我想创建动态字符数组来存储字符串。

这是我的代码:

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

int main(void)
{
int i , j , n;
char *ptr;
printf("enter number of elements \n");
scanf("%d",&n);
ptr = (char *) malloc((n + 1)*sizeof(char));
for (i = 0;i< n;i++)
{
scanf("%c",&ptr[i]);
}
for ( i = 0;i <n; i++)
{
printf("at %d is %c\n",i,*(ptr + i));
}
free(ptr);
}

但是当我尝试编译和运行这段代码时,没有字符分配给指针 p 指向的内存。

这是我的程序的输出:

jharvard@appliance (~/c): ./test2
enter number of elements
8
asdfghjk
at 0 is
at 1 is a
at 2 is s
at 3 is d
at 4 is f
at 5 is g
at 6 is h
at 7 is j

最佳答案

scanf中的%c前留一个空格-

scanf(" %c",&ptr[i]);

因为当您按 ENTER 在给出 n 的值之后。

而且您不需要转换 malloc 的结果。

正如 Matt McNabb Sir 在他的评论中所说的那样,您可以这样做 -

 scanf("%*c%c",&ptr[i]);

%*c 将处理 '\n' 并且如果只点击 space 甚至不会跳过。

关于c - 使用 malloc 分配动态内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32269636/

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