简体   繁体   中英

Dlang associative array of arrays

I am building an associative array of arrays. I tried using an appender, but am getting a segfault. What is the correct way to do this? Below is small test program:

import std.stdio;
import std.array;

struct Entry {
    string ip;
    string service;
}


void main(string[] args) {
    Entry[3] ents;
    ents[0] = Entry("1.1.1.1", "host1");
    ents[1] = Entry("1.1.1.2", "host2");
    ents[2] = Entry("1.1.1.1", "dns");

    string[][string] ip_hosts;

    foreach (entry; ents) {
        string ip = entry.ip;
        string service = entry.service;

        string[] *new_ip = (ip in ip_hosts);
        if (new_ip !is null) {
            *new_ip = [];
        }
        auto app = appender(*new_ip);
        app.put(service);
        continue;
    }
    writeln("Out:", ip_hosts);
}

I think this may have to do with using a pointer to a list with the appender, but I'm not sure. Does anyone know what's wrong, and a good way to fix the issue?

This bit here is buggy regardless:

    string[] *new_ip = (ip in ip_hosts);
    if (new_ip !is null) {
        *new_ip = [];
    }
    auto app = appender(*new_ip);

What if new_ip is null (which is what happens the first time every time...)? It would still be null when you try to dereference it below!

Try changing it to something like this:

    string[] *new_ip = (ip in ip_hosts);
    if (new_ip is null) { // check if it is null instead of if it isn't
        ip_hosts[ip] = []; // add it to the AA if it is null
        // (since it is null you can't just do *new_ip = [])
        new_ip = ip in ip_hosts; // get the pointer here for use below
    }
    *new_ip ~= service; // just do a plain append, no need for appender

Making a new appender each time through the loop is a waste of time anyway, you don't gain anything from it since it doesn't get to reuse its state twice.

But if you did want to use it:

    auto app = appender(*new_ip);
    app.put(service);
    *new_ip = app.data; // reassign the data back to the original thing

You'd need to reassign the data to the AA so it gets saved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM