0

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.

6
  • 2
    What is tableptr in main? Is that some hidden global? Or is this not the code you're running? Commented Sep 17, 2022 at 2:43
  • 1
    Also, what do you mean by "doesn't seem to work"? What does it do? Besides, if you intended to pass table to your function, notice that nothing is preventing the second while loop from accessing out of bounds of the array, and writing there. Commented Sep 17, 2022 at 7:02
  • Your array is static and therefore initialized to 0. Passing a NULL pointer to printf causes undefined behavior. In some implementations a "(nul)" is printed but you should not rely on that. Commented Sep 17, 2022 at 8:49
  • From How-to-ask: "Post the question and respond to feedback. After you post, leave the question open in your browser for a bit, and see if anyone comments." Commented Sep 17, 2022 at 8:58
  • @TomKarzes tableptr is a typo, I meant to write table. @aulven I mean that the final printf does not print a changed table[2].fd as intended, even though it does find that [2] is available. @Gerhardh indeed it prints (null). Commented Sep 17, 2022 at 12:39

1 Answer 1

1

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); } ... 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.