Writing to a struct element in c

Viewed 33

I have the following struct:

struct      fdtable
{
    int     fd;
    char    *ptr;
};

and in my code, I can declare a variable to it, and assign some values in the main, and this works.

int main()
{
    static struct fdtable   table[100];
    int                     i;

    table[0].fd = 5;
    table[1].fd = 6;
    table[0].ptr = strdup("Hello");
    table[1].ptr = strdup("How do you do?");
    printf("fd1: %i, ptr1: %s\n", table[0].fd, table[0].ptr);
    printf("fd2: %i, ptr2: %s\n", table[1].fd, table[1].ptr);
    printf("fd3: %i, ptr3: %s\n", table[2].fd, table[2].ptr);
    table[1].ptr = remaining(table[1].ptr);
    printf("fd2: %i, ptr2: %s\n", table[1].fd, table[1].ptr);
    i = readtable(9, tableptr);
    printf("fd3: %i, ptr3: %s, i: %i\n", table[2].fd, table[2].ptr, i);
    return (0);
}

However in my readtable function I also want to change some elements and it doesn't seem to work.

unsigned int    readtable(int fd, struct fdtable *ptrtable)
{
    unsigned int    i;
    unsigned int    j;

    if (fd == 0)
        return (0);
    i = 1;
    while (fd != ptrtable[i].fd && ptrtable[i].ptr != 0 && i < 100)
        i++;
    if (i == 100)
    {
        j = 1;
        while (ptrtable[j].fd != 0)
            j++;
    ----ptrtable[j].fd = fd;----
        return (j);
    }
    else
        return (i);
}

I'm probably just not understanding something simple about how to use a struct.

1 Answers

So, I was calling the pointer in the wrong way at the while loop, such that it only incremented once, and never entered the i=100 condition. I think it was a notation mistake. This code works:

... 
i = 1;
while ((ptrtable + i)->fd != fd && i < 100)
    i++;
if (i == 100)
{
    j = 1;
    while (ptrtable[j].fd != 0 && j < 100)
        j++;
    (ptrtable + j)->fd = fd;
    return (j);
}
...
Related