Access a Array by Struct (with a pointer)

Viewed 40

I was trying to access a array by a simple struct:

int demo()
{

    typedef struct {
        void *things; // 1st element of my array
        int sizeOfThings;
    } Demo;

    typedef struct {
        void *A; // 
        int A;
        int visited
    } element; // my element struct

    Demoarray[4]={"A","B","C","D"); // each element using struct element.

    Demo->things = A;
    return Demo;
}

I can successfully creat my array and my Demo node, but can I access this Demoarray in other functions simply by using my demo node? and how can I do it? Do I have to make my Demoarray[4] a golble variable?

1 Answers

You need to declare the struct outside your function if you want other functions to understand its size, padding, alignment, etc and to just use it in general.

Your array also needs to be allocated on the heap rather than the stack because once your function returns, that pointer could be lost due to the stack pointer shifting up and down.

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

struct Demo {
        void *things; // 1st element of my array
        int sizeOfThings;
} ;

void createthings(struct Demo* d) {
    char* things = malloc(4);
    for(char i = 0; i < 4; ++i){
        things[i] = i+0x41;
    }
    d->things = things;
    d->sizeOfThings = 4;
}

int main() {
    struct Demo d = {0};
    createthings(&d);
    for(char i = 0; i < d.sizeOfThings;++i){
        printf("%c ",*(char*)(d.things+i));
    }
    free(d.things);
    return 0;
}

This will create a structure in main, pass it's pointer to createthings, createthings will create an array of size 4 allocated on the heap, assign it values 'A','B','C','D', then print them out in main and lastly free the memory.

Related