以下代码可以工作吗? [英] Will the following code work ?

查看:61
本文介绍了以下代码可以工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct data 
{
 char name[80];
 double age;
}
 const data MyStruct = {"a",1000};
 strcpy(MyStruct.name,"p");
 printf(MyStruct.name);


请解释此代码是否有任何问题.还是可以吗?比为什么呢?


Please explain if this code has any problem. Or is it okay? Than why?

推荐答案

除了SA指出的问题之外,从查看代码的作用来看,它在概念上是错误的……您已经声明了一个常量结构,那么您要在事后将其他字符串复制到字符缓冲区中.
besides the problems that SA pointed out, from looking at what that code is doing, its conceptually wrong... you''ve declared a constant structure then you''re trying to copy a different string onto your character buffer after the fact.


好吧,由于4个立即数经过硬编码,因此它不是一种完美的样式.它也无用地消耗了80个字节的内存,但这是由于静态数组的性质.对我来说,以空终止的字符串是技术历史上最糟糕的想法之一,但这不是你的错:-).您可以改用std::string.

函数strcpy不安全,最好使用strcpy_s.
在结构声明之后,您需要;".
由于data之前的const,因此无法编译代码.

现在,我可以理解,如果您的代码甚至没有编译,甚至没有报告此问题,您为什么要问这样的问题?您甚至尝试编译它吗?
看起来您正在尝试将过多的工作放在别人身上,但这对您没有太大帮助.

我必须说,您的学习方法无效.我建议您不要在CodeProject上问这样的问题,并使用一些很好的手册和练习来学习基础知识,并使用我在此处概述的方法:
我的程序有问题.请帮忙! [
Well, it''s not a perfect style because of 4 immediate constants hard-coded. It also consumes 80 bytes of memory without purpose, but this is because of the nature of static array. To me, null terminated string was one of the worst ideas in the history of technology, but this is not your fault :-). You could use std::string instead.

The function strcpy is unsafe, better use strcpy_s.
After the structure declaration you need '';''.
The code will not compile because of const before data.

Now, may I understand why are you asking such Question if your code does not even compile, and you even did not report this problem? Did you even try to compile it?
It looks like you''re trying to put too much of your job on others, but it does not help you much.

I must say, your method of learning is not effective. I advice you stop asking such Questions here at CodeProject and learn the basics using some good manual and exercises, using the approach I outlined here:
I have a problem with my program. Please help![^].

—SA


这篇关于以下代码可以工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆