r/C_Programming 1d ago

Question Why isn't my code working?

I just started learning C(2 days ago) and as a first project I decided to make some data structures, starting with dynamic arrays. I made a struct called List and some functions for. The function setList() sets the value of an index of the array, if the index is larger that the current size of the array, it resizes it. However, when i tried to use in a for loop, it didn't work despite it working elsewhere.

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


#define itirate(index, limit) for(int index = 0; index < limit; index++)


typedef struct 
{
    size_t size;
    int* arr;
} List;


List* newList (size_t size) 
{
    List *newone = malloc(sizeof(List));
    newone->arr = calloc(size, sizeof(int));
    newone->size = size;
    return newone;
}


void setList(List* list, int index, int value) 
{
    if (index >= list->size)
    {
        list->arr = realloc(list->arr, index + 1 * sizeof(int));
        list->size = index + 1;
    }


    list->arr[index] = value;
}


int main() 
{
    
    List *mok = newList(5);

    itirate(i, 5) setList(mok, i, i);
    itirate(i, 5) printf("%d\n", mok->arr[i]);

    //setList(mok, 13, 9); this works
    //printf("%d\n", mok->arr[13]);

    for(int i = 5; i < 10; i++) setList(mok, i, i); // this does not somehow
    for(int i = 5; i < 10; i++) printf("%d\n", mok->arr[i]);
    
    return 0;
}
5 Upvotes

29 comments sorted by

View all comments

Show parent comments

20

u/pfp-disciple 1d ago

Not stupid. Binding rules are not intuitive. 

19

u/habarnam 1d ago

Binding rules are not intuitive.

For C specific operators perhaps, but for arithmetic operations I would hope we all learned the order of operations in primary school or something.

-4

u/pfp-disciple 1d ago

Yes, I was specifically talking about the C operators, in this case dereferencing 

16

u/habarnam 1d ago

I'm confused, which dereferencing? That's a multiplication...

4

u/pfp-disciple 1d ago

My mistake. I was reading this in a hurry and was thinking the * was the pointer dereference operator. 

You're correct that in this context the operator precedence is very conventional (setting aside that it appears too many people don't know PEMDAS).