您的位置:首页 > 编程语言 > C语言/C++

一个很好的c++指针面试题 想当年我只对了一个,现在回头看,还是错的一塌糊涂

2016-03-01 17:01 399 查看
//参数为指针 实际上也是值传递 实参与型参是两个不同的概念

void GetMemory1(char *p, int num)

{

p = (char*)malloc(num);

}

void Test1(void)

{

char *str = NULL;

GetMemory1(str, 100);

strcpy(str, "hello world");

printf("%s\n", str);

}

//型参为指针的指针 实际也就是指针的引用 对指针的操作可以认为是同一个东西

void GetMemory2(char **p, int num)

{

*p = (char*)malloc(num);

}

void Test2(void)

{

char * str = NULL;

GetMemory2(&str, 100);

strcpy(str, "hello world");

printf("%s\n", str);

free(str);

}

char* GetMemory3(void)

{

//栈内存

char p[] ="hello world";

return p;

}

void Test3(void)

{

char* str = NULL;

str = GetMemory3();

printf("%s\n", str);

}

char* GetMemory4(void)

{

//常量区

char *p = "hello world";

return p;

}

void Test4()

{

char* str = NULL;

str = GetMemory4();

printf("%s\n", str);

}

char* GetMemory5(void)

{

char *p = (char*)malloc(100);

strcpy(p,"hello world");

return p;

}

void Test5()

{

char* str = NULL;

str = GetMemory5();

printf("%s\n", str);

free(str);

}

void Test6( void )

{

char * str = (char*)malloc(100);

strcpy(str, "hello");

free(str);

if (str != NULL)

{

strcpy(str, "world" );

printf("%s\n",str);

}

}

int main()

{

Test1();

while(1);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: