据我所知,从返回类型函数接收到的值必须存储在调用它的地方,否则它是错误的。请解释下面的代码如何正常工作。
#include <iostream>
#include <stdlib.h>
#include<assert.h>
//Returns a pointer to the heap memory location which stores the duplicate string
char* StringCopy(char* string)
{
long length=strlen(string) +1;
char *newString;
newString=(char*)malloc(sizeof(char)*length);
assert(newString!=NULL);
strcpy(newString,string);
return(newString);
}
int main(int argc, const char * argv[])
{
char name[30]="Kunal Shrivastava";
StringCopy(name); /* There is no error even when there is no pointer which
stores the returned pointer value from the function
StringCopy */
return 0;
}
我在 Xcode 中使用 c++。
谢谢你。