Domanda

I've hit a wall with a program that uses embedded SQL to fetch rows from a database table, stores the row data in a struct, and then has that data processed with results being stored in another struct and pushed to a linked list. The struct that where the fetch data is stored is as follows:

struct rowstruct {
    char    *first;
    char    *last;
    long    amt;
}   client;

and my struct that I use to store the processed data (and subsequently push as a node in my linked list) is like this:

struct mystruct {
        char    *firstN;
        char    *lastN;
        long    total;
    }   data;

My problem is that with each fetch loop that occurs, I need to copy the client.first and client.last values into data.firstN and data.lastN, but I can't get it to work. The following, using the assignment operator, just seems to be copying the pointer, rather than the value:

data.firstN = client.first;
data.lastN = client.last;

If I output data.firstN and data.lastN after the first iteration of my loop, the values appear correct, but after the second fetch iteration, the first node in my list will reflect the values from the second fetch, rather than the first.

strcpy will compile, but fails at runtime due to segmentation fault, which from reading on here is due to the char* being used, though I don't think I can use char[] or string when fetching the data using embedded SQL, so that seems like a dead end.

I'm sure there's a way to do this, and it's probably obvious to most here, but I'm at a loss. Any help would be appreciated.

Thanks!

È stato utile?

Soluzione

If the code says to copy the pointer, that is exactly what happens.

Probably what you want is something along the lines of

data.firstN = strdup (client.first);
data.lastN = strdup (client.last);

There are more C++-ish ways of doing the same thing, but this should get you over the hump.


You don't need to re-declare the structure. Instead, you can declare data with

struct rowstruct data;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top