C指针笔试题找错误-。-进来看看

C语言 码拜 7年前 (2017-04-19) 936次浏览
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun(char *p)
{
p=(char *)malloc(100);
}
int main(int argc, char const *argv[])
{
char *src=NULL;
fun(src);
strcpy(p,”hello world”);
printf(“%s\n”,src );
return 0;
}
解决方案

40

一  语法上把strcpy(p,”hello world”);改成strcpy(src,”hello world”);这里应该是笔误吧,否则无法编译.
二 fun函数中你的型参是char*,你传得实参是src的一个副本,因此src不会只想你分配的那100个字节
要这样改:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun(char** p)
{
    *p=(char*)malloc(100);
}
int main(int argc, char const *argv[])
{
    char *src=NULL;
    fun(&src);
    strcpy(src,"hello world");
    printf("%s\n",src );
    return 0;
}

结果:
hyman@hyman-laptop:~/test$ gcc -g test.c
hyman@hyman-laptop:~/test$ ./a.out
hello world


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C指针笔试题找错误-。-进来看看
喜欢 (0)
[1034331897@qq.com]
分享 (0)