使用指针或引用来构造 [英] Using pointers or references to struct

查看:95
本文介绍了使用指针或引用来构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我的朋友在我们的代码中使用了结构(我们的代码彼此分开).让我们以以下示例为例:

Me and my friend is using structs in our code (our code is separate from each other). Lets take the following example:

struct Book {
     char title;
     int pages;
}

void setBook(struct Book *tempBook) {
     tempBook->title = "NiceTitle";
     tempBook->pages = 50;
}

上面的代码非常简单.问题是,拥有这两个主要要素有什么区别:

The above code is pretty straight forward. The thing is, is there any difference in having these two mains:

 int main() {
     struct book obj1;
     setBook(&obj);
    }

int main() {
    struct Book *obj2;
    setBook(obj2);
}

我的发言不清楚.我已经初始化了

I was not clear in my statement. I have initialized the pinter to

struct Book *obj2 = malloc(sizeof(struct obj2));

推荐答案

如果

 struct book obj1;
 setBook(&obj);

您要将有效地址#1 传递给函数,因此行为已定义.

you're passing a valid address#1 to the function, so the behaviour is defined.

另一方面,

struct Book *obj2;
setBook(obj2);

您正在传递统一的指针#2 ,该访问会调用未定义行为.

you're passing an unitialized pointer#2, accessing which invokes undefined behavior.

也就是说,成员char title;应该是char *title;,因为字符串文字在用作初始值设定项时会衰减到指向第一个元素的指针,因此您将需要一个指针在LHS上.

That said, the member char title; should be char *title;, as the string literal, when used as initializer, decays to the pointer to the first element, so you'll need a pointer on the LHS.

#1-obj1是自动局部变量,并且该变量的地址是作用域中的有效地址.

#1 -- obj1 is an automatic local variable, and address of that variable is a valid address in the scope.

#2-struct Book *obj2;定义了一个指针,obj2再次是一个自动局部变量,它没有隐式初始化为任何东西.因此,初始值(即指针指向的内存地址)是不确定的,并且无效非常好.

#2 -- struct Book *obj2; defines a pointer and again, obj2 being an automatic local variable, it is not implicitly initialized to anything. So, the initial value (i.e., the memory address at which the pointer points) is indeterminate and pretty well invalid.

这篇关于使用指针或引用来构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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