下面是我的代碼示例。我想創建動態字符數組來存儲字符串。使用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結尾 –