阿摩線上測驗 登入

申論題資訊

試卷:110年 - 110-2 國立清華大學期末考試題_電機工程學系:計算機程式設計#112945
科目:程式設計
年份:110年
排序:0

題組內容

3. (15%) Consider the access of dynamically allocated data structure.
63c0b6613025d.jpg

申論題內容

(b) Fill in Statement-1 in the following program that assigns a dynamic S_record object and returns its starting address to variable ptr_s. (5%)

詳解 (共 1 筆)

詳解 提供者:hchungw

In the provided context where you're looking to assign a dynamic S_record object and return its starting address to a variable ptr_s, the appropriate way to do this in C++ is by using the new operator. The new operator dynamically allocates memory for an object of a given type and returns a pointer to the beginning of that memory block, which is the starting address of the object.

If S_record is a class or struct, and ptr_s is supposed to point to an instance of S_record, then Statement-1 would be:

 
ptr_s = new S_record;

This line dynamically allocates memory for an S_record object and assigns its address to ptr_s, which should be declared as a pointer of type S_record*. This way, ptr_s now points to a dynamically allocated S_record object.

 

在提供的情境中,如果你希望分配一個動態的S_record對象並將其起始地址返回給變量ptr_s,在C++中適當的做法是使用new運算子。new運算子為給定類型的對象動態分配內存,並返回該內存塊的開始指針,即對象的起始地址。

如果S_record是一個類或結構體,且ptr_s應該指向一個S_record的實例,那麼Statement-1將會是:

 
ptr_s = new S_record;

這行代碼為一個S_record對象動態分配內存並將其地址賦值給ptr_s,ptr_s應該被聲明為S_record*類型的指針。這樣,ptr_s現在指向一個動態分配的S_record對象。