Search code examples
cfunctionstructtypedefstrcpy

how to change a character array in typedef struct from a function?


i'm trying to change array a inside set of typedef through function readset but it doesn't do anything to it and im trying to understand how to use a pointer so i would just send it to the function but its not working how to do that?

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

typedef struct set {
    char a[128];
}set;

 set SETA={""};

void readset (set rset)
{
    char tmp[128];
    int i;
    i=0;
    while(i<128)
        rset.a[i++]='0';
    i=0;
    while(i<128)
        tmp[i++]='0';

        tmp[arr[1]-1]='1';
    strcpy(rset.a, tmp);
    printf("tmp in function is: %s\n",tmp);

}

int main()
{
    int i=0;

    while(i<128)
        SETA.a[i++]='0';
    printf("\n");
    printf("setA before: %s\n",SETA.a);
    readset(setPtr);
    printf("setA after: %s\n",SETA.a);

return 0;
} ```

Solution

  • Say you have a struct, defined like this:

    typedef struct bar_s
    {
        char data[128];
        int someInt;
    } bar_t;
    

    You would define your function like this:

    void foo(bar_t* p) //Note the asterisk
    {
        strcpy(p->data, "Hello!"); //copy a string into data field
        p->someInt = 0; //assign value to someInt field. Note the "->"
        (*p).someInt = 0; //Same as above, using a dereference operator.
    }
    

    Now how do you pass a pointer to this function? You would do something like this:

    bar_t sample;
    foo(&sample); // & = address-of operator.
    

    Your readSet function needs a bit of work to get it functional, but that's how to work with pointers in C. In your case you would do something like this:

    void readSet(set* rset)
    {
        int i = 0;
        for(i = 0; i < 127; ++i)
        {
            rset->a[i] = '0';
        }
    
        //Note that all strings in C must be terminated with a null character.
        //So, let's put one at the last place in the array.
        rset->a[127] = '\0';
        ...
    }