1

After entering the second element, it throws me out x. I know that allocating memory for each element is not appropriate, but I wanted to better detect errors.I want to save two character fields for which I do not know the size in advance.

typedef struct
{
    char *m_Cislo;  
    char *m_Jmeno;
} TSEZNAM;

TSEZNAM * readNumbers (int *nr)
{   
    char *str = NULL;
    size_t  capacity = 0;

    TSEZNAM st;
    TSEZNAM *res = NULL;
    *nr=0;
    
    while ( getline(&str, &capacity, stdin) != -1 )
    {

        st.m_Jmeno = malloc(sizeof(char)*capacity);
        st.m_Cislo = malloc(sizeof(char)*capacity);
        
        sscanf(str,"%s %s", st.m_Cislo, st.m_Jmeno);

        TSEZNAM *tmp = (TSEZNAM*) malloc ((*nr+1)*sizeof(*res));

        for(int i=0; i < *nr; i++)
            tmp[i] = res[i];
            
        free(res);
        res=tmp;

        res[*nr]=st;
        *(nr)++;
        
    }
    
    return res;
}

int main(void)
{
    int listNr;
    TSEZNAM *list = readNumbers(&listNr);       
    
}
0

1 Answer 1

1

The parentheses in your *(nr)++; statement actually achieve nothing (you are simply wrapping the name of the nr variable); thus, the effect of this statement is to increment the value of the pointer - which will cause problems in the second (and subsequent) loop(s), because it will then be pointing to an invalid location. This is because the post-increment (++) operator has higher precedence than the indirection (*) operator.

In fact, with full warnings enabled, your compiler will likely find this problem; for example, clang-cl gives:

warning : expression result unused [-Wunused-value]

To fix the problem, you need to place the dereference operator (*) inside the brackets, like this: (*nr)++.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.