Saturday, July 9, 2022

[FIXED] How do you use the user keyword "list"?

Issue

For a practical work I am working on I have to use a "preset" structure for certain functions. One of them was as follows:

int initEmployees(Employee* list, int len)
{

//From here is my code

    int isError = -1;
    if ( len > 0)
    {
        len--;
        for (int i = 0 ; i < len ; i++)
        {

//This line is the problem, I know is not right but not sure how to fix it
            list[i].isEmpty = 1;

/*My other guesses where:
*(list + i).isEmpty = 1;
(*Employee + i).isEmpty = 1;
but im quiet sure they won't work either*/

        }
        isError=0;
    }
    return isError;
}

Tried googling it: "Is codeblocks user keyword releted to STL!" and going through a 1991 C book (Spanish edit) checking if it contined references to any library containing it but nothing.


Solution

First up, list in this context is a variable name, not a keyword.

And there's nothing wrong with that loop code, provided that the Employee structure actually has an isEmpty member that you can assign 1 to.

It simply runs through a provided array (called list), setting each element in turn to be empty.

However, your manipulation of len seems a bit off, I suspect it won't modify the last element in the list since you decrement it before running the loop.

I suspect a more canonical version (including that fix) would be something like:

int initEmployees(Employee* list, int len) {
    // Error if no elements in list.

    if (len < 1) return -1;

    // Mark each entry as empty.

    for (int i = 0 ; i < len ; i++) {
        list[i].isEmpty = 1;
    }

    // Everything is okay.

    return 0;
}

But I'd also question raising an error on a list size of zero. It seems to me that it's perfectly okay to modify all elements of an empty list - that just involves doing nothing.

And, if you use unsigned values for sizes of things (e.g., size_t), your "negative" problem goes away.



Answered By - paxdiablo
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.