C语言------这样是否多此一举

#include "stdio.h"
#include "string.h"
main()
{
char *pstr="I am a student",*pstr2;
char string[15];
pstr2=string;
strcpy(pstr2,pstr);
printf("%s\n",pstr2);
}

问题:此程序可以改成如下形势也可以运行,上面不就多此一举了吗?

#include "stdio.h"
#include "string.h"
main()
{
char *pstr="I am a student";
printf("%s\n",pstr);
}
这时讲指针的例子

第1个回答  2007-08-30
是讲解字符串复制函数的用法:
现在用这个函数的不多,一般都用sprintf();
c++里面有string这个类 就不必这么麻烦了

#include <string.h>

char *strcpy(char *dest, const char *src);

char *strncpy(char *dest, const char *src, size_t n);

DESCRIPTION
The strcpy() function copies the string pointed to by src (including
the terminating `\0' character) to the array pointed to by dest. The
strings may not overlap, and the destination string dest must be large
enough to receive the copy.本回答被网友采纳
第2个回答  2007-08-30
main()
{
char *pstr="I am a student",*pstr2;
char string[15];
pstr2=string;
strcpy(pstr2,pstr);
printf("%s\n",pstr2);
}
它是把一个pstr指向的I am a student字符串复制到字符数组string[15]中.
你改的和原来的结果是一样,但可改的哪个只是把pstr指向的I am a student字符串输出并没有给字符数组string[15]赋值.
上面的比你的多了个功能啊!!!!!!!!!!!!!!!!!!!!!
第3个回答  2007-08-31
#include "stdio.h"
#include "string.h"
main()
{
char *pstr="I am a student";/*定义指针,分配内存,并赋值*/
char *pstr2; /* 定义指针 */
char string[15];
pstr2=string; /* 指针赋值 */
strcpy(pstr2,pstr); /* 指针作为函数参数 */
printf("%s\n",pstr2);
}

范例就无所谓"多此一举"了,应该是越多越好,让你看看指针都可以怎么用
第4个回答  2007-09-09
这个问题是个老问题了。
在C里面,
如果这样
char *pstr="I am a student";
声明一个变量并赋值,是有可能出错误的(内存写入错误等)。
必须要指定字符串的长度。
也就是说用数组来定义,并且直接赋值。
第5个回答  2007-08-30
这个程序是说把指针pstr所指的字符串复制到字符串数组string[15]中

strcpy()是复制字符串命令
相似回答