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.
tableptrinmain? Is that some hidden global? Or is this not the code you're running?tableto your function, notice that nothing is preventing the secondwhileloop from accessing out of bounds of the array, and writing there.NULLpointer to printf causes undefined behavior. In some implementations a"(nul)"is printed but you should not rely on that.tableptris a typo, I meant to writetable. @aulven I mean that the final printf does not print a changedtable[2].fdas intended, even though it does find that[2]is available. @Gerhardh indeed it prints (null).