注册 登录
编程论坛 C++教室

编写一个程序,使用定位new运算符将一个包含两个这种的结构 的数组放在一个缓冲区中,然后给成员赋值,并使用循环查看内容

C00000001 发布于 2021-05-20 14:50, 3357 次点击
使用结构声明
    struct chaff
    {
        char dross[20];
        int slag;
    };
编写一个程序,使用定位new运算符将一个包含两个这种的结构
的数组放在一个缓冲区中,然后给成员赋值,并使用循环查看内容
头文件golf.h
namespace golf
{
    struct chaff
    {
        char dross[20];
        int slag;
    };
    typedef struct chaff Str_Cha;
    typedef Str_Cha* Str_Cha_pointer;
    void show(Str_Cha_pointer* pd, int n);
}
源代码1
#include<iostream>
#include"golf.h"
namespace golf
{
    void show(Str_Cha_pointer* pd,int n)
    {
        for (int i = 0; i < n; i++)
        {
            std::cout << "Dross: " << pd[i]->dross << std::endl;
            std::cout << "Slag: " << pd[i]->slag << std::endl;
        }
    }
}
源代码2
#include<iostream>
#include"golf.h"
#include<new>
int main()
{
    using namespace std;
    char buffer[500];
    golf::Str_Cha* pd = new (buffer)golf::Str_Cha[2];
    int i = 0;
    do
    {
        std::cout << "Enter the dross:";
        std::cin.getline(pd[i].dross, 20);
        std::cout << "Enter the slag:";
        std::cin >> pd[i].slag;
        std::cin.get();
        i++;
    } while (pd[i-1].dross[0]!='\0'&& i < 2);
    golf::show(&pd,2);
    delete[]pd;
    return 0;
}
执行出错了
5 回复
#2
C000000012021-05-20 14:53
golf::show(&pd,2);
这里是不是这指针出错了
#3
rjsp2021-05-20 16:58
程序代码:
#include <iostream>
#include <cstring>

namespace golf
{
    struct chaff
    {
        char dross[20];
        int slag;

        chaff( const char* dross_, int slag_ ) : slag(slag_)
        {
            strcpy( dross, dross_ );
        }
    };

    std::ostream& operator<<( std::ostream& os, const chaff& obj )
    {
        return os << "Dross: " << obj.dross << '\n'
                  << "Slag: " << obj.slag;
    }

}

#include <new>
using namespace std;
using namespace golf;

int main( void )
{
    char buffer[ 2 * sizeof(golf::chaff) ];
    chaff* p = new (buffer)chaff[2]{ chaff("a",1), chaff("b",2) };
    for( size_t i=0; i!=2; ++i )
        cout << p[i] << '\n';
}
#4
rjsp2021-05-20 17:02
回复 2楼 C00000001
最后的 delete[]pd; 也是不对的。
没有 new 就没有 delete。( placement new 不是 new
#5
C000000012021-05-20 18:40
回复 4楼 rjsp
new分配内存
struct inf *pd=new struct [10]
的地址是不是pd?
#6
rjsp2021-05-20 21:12
回复 5楼 C00000001
是,但不知道你问这个是什么意思
1