lightyears99
lightyears99

Reputation: 111

How do I keep information in struct after returning from function?

So I am still a little confused about pointers in connection with structs. I have a struct which represents a queue. The queue contains an array of queue elements (containers). I now want to access these containers in order to assign values to them. This code is only for containers[0] to keep it simple.

How can I access the string at containers[0] in main after returning from writeContainer() function?

The signature of writeContainer() is given, so I can't change that.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct qElement {
    char array[55];
    int len;
} container;

typedef struct queue {
    container containers[5];
    int id;
} myq;

int writeContainer(myq anyq, void *buf, int buflen);

int main(void) {
    myq *testq = malloc(sizeof(myq));
    char *mainArray = "hello";

    writeContainer(*testq, mainArray, 6);

    printf("outside Array[0]: %s\n", testq->containers[0].array);
    return EXIT_SUCCESS;
}

int writeContainer(myq anyq, void *buf, int buflen) {
    container *elem = malloc(sizeof(container));

    // into temp elemnt
    elem->len = buflen;
    memcpy(&elem->array, buf, buflen);

    // into actual queue
    memcpy(&anyq.containers[0], elem, buflen);
    printf("qArray[0]: %s\n", &anyq.containers[0].array);
    printf("exiting function\n");
    free(elem);
    return buflen;
}

so the output is:

qArray[0]: hello
exiting function
outside Array[0]: 

but I expected:

qArray[0]: hello
exiting function
outside Array[0]: hello

Thanks in advance

Upvotes: 2

Views: 273

Answers (1)

chqrlie
chqrlie

Reputation: 144969

With this prototype for writeContainer:

int writeContainer(myq anyq, void *buf, int buflen);

and the posted definition of myq, writeContainer cannot be written to have a side effect on the queue passed from main() because it is passed by value. The prototype is inconsistent on another aspect: if data from buf is only supposed to be read and copied to the container(s), this pointer should be declared as const void *buf and its size should be passed as a size_t buflen.

There is a * missing, either in the prototype or in the typedef for myq.

Upvotes: 1

Related Questions