char *toParseStr = (char*)malloc(10);
printf("Enter string here: ");
scanf("%s",toParseStr);
printf("%s",toParseStr);
free(toParseStr);
首先,
scanf
中的字符串指定了它要接收的输入。为了在接受键盘输入之前显示一个字符串,请使用
printf
如下所示。
其次,你不需要解引用
toParseStr
,因为它指向大小为 10 的字符数组,而你已经使用
malloc
分配了内存。只有当你使用一个函数将其指向另一个内存位置时,才需要使用
&toParseStr
。
例如,假设你想编写一个分配内存的函数,那么你就需要
&toParseStr
,因为你正在更改指针变量的内容(它是内存中的一个地址 --- 你可以通过打印它的内容来查看)。
void AllocateString(char ** ptr_string, const int n)
{
*ptr_string = (char*)malloc(sizeof(char) * n);
}
如您所见,它接受 char ** ptr_string
,它的意思是指向存储指针内存位置的指针,该指针将会存储分配了n
个字节的内存块的第一个字节的内存地址(现在由于未初始化,它具有一些垃圾内存地址)。
int main(int argc, char *argv[])
{
char *toParseStr;
const int n = 10;
printf("Garbage: %p\n",toParseStr);
AllocateString(&toParseStr,n);
printf("Address of the first element of a contiguous array of %d bytes: %p\n",n,toParseStr);
printf("Enter string here: ");
scanf("%s",toParseStr);
printf("%s\n",toParseStr);
free(toParseStr);
return 0;
}
第三,建议您释放您分配的内存。即使这是您的整个程序,在程序退出时此内存将被释放,但这仍然是一个良好的实践。
<stdlib.h>
头文件包含时,您不需要将malloc(3)
的返回类型强制转换。 - sarnold