下面是我的代码示例。我想创建动态字符数组来存储字符串。使用malloc分配动态内存
这里是我的代码:
#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
内存。
这里是我的程序的输出:
[email protected] (~/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
请[不要施放malloc的结果](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc?lq=1)。 – Martin
请注意'sizeof(char)'总是1,所以你可以用'ptr = malloc(n + 1);'替换分配。 – user694733
作为int main(),你应该至少返回0到0结尾 –