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