Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C- Setting a array of structs to null

so sorry if I am a little confused.

I am trying to fill out an array of structs with values I read in from an input file. I am having no trouble reading in the values from the file. But when the file is very small and does not fill the array completely, the remaining structs have random values in them, and I would like to completely set these structs to NULL. I am attempting to do this because I would like to run through this filled out array of structs and print its values, and I need to see which array values are legitimately from the file.

Here is my code so far

struct function {
    char name[20];
    int parameterNumer;

};


int main(int argc, const char * argv[])
{
    struct function functionList[10];
    int i =0, j;
    int portNumber;
    char *configFile = argv[1];
    FILE *fp;

    fp = fopen(configFile, "r");
    if(fp == NULL) {
        perror("File not found");
        exit(1);
    }

    fscanf(fp, "%d", &portNumber);
    while(fscanf(fp, "%s %d", functionList[i].name, &functionList[i].parameterNumer) == 2) {
        i++;
    }
    functionList[i] = NULL; //getting an error here

    for(j = 0; functionList[j] != NULL; j++) {  //and here
        printf("%s %d", functionList[j].name, &functionList[j].parameterNumer);
    }


    return 0;

}
like image 470
user2158382 Avatar asked Mar 24 '23 06:03

user2158382


2 Answers

Initialize the array:

/* Remaining elements zero-d. */
struct function functionList[10] = { { "", 0 } };

if an empty string or a zero indicates an unpopulated entry in the array and then use either an empty string or zero int to terminate the for:

for(j = 0; strlen(functionList[j].name); j++) {

for(j = 0; functionList[j].parameterNumber; j++) {

Additionally, prevent out of bounds access on functionList in the while:

while(i < 10 && fscanf(fp,
                       "%s %d",
                       functionList[i].name,
                       &functionList[i].parameterNumer) == 2)
{
    i++;
}

Note that the value of i after this while would also provide a terminating condition for the subsequent for loop:

for (j = 0; j < i; j++) {
like image 144
hmjd Avatar answered Mar 26 '23 19:03

hmjd


You could create the array with a calloc()

struct function* functionList = calloc(sizeof(struct function), 10);

and change to this pointer where the array is referenced, in this way the struct is created with all zero in it.

like image 21
gipi Avatar answered Mar 26 '23 21:03

gipi