Home > front end >  Why isn't NULL being assigned to my array of pointers?
Why isn't NULL being assigned to my array of pointers?

Time:10-02

I have this C program in which the last position in the *args array must be NULL. The NULL isn't being assigned or maybe printed? Is it because "%s" doesn't work with NULL?

In the program below I'm splitting a user inputted string and assigning each token to the *args array of pointers. The last element shall be NULL.

CodePudding user response:

As noted above you don't count the NULL (unless it was the first one; bug) so this means args[counter -1 ] will be the last non-NULL entry when you print it. Here are some issues that I fixed:

  • Replaced run flag with a break, which eliminated the need including stdbool
  • args is subject to overflow
  • It doesn't make sense to do a bunch of work on exit so moved that to right after input
  • streamline strtok call, and fixed defect if first call returns NULL
  • Prettify output including changing message "last character" to "last string".
  • Replaced the two magic values of 81 with defines.

And a few issues not fixed:

  • You use both a terminating null and a counter to significant number of elements in args. Choose one or the other.
  • scanf is subject to buffer overflow, replace it with fgets() and post-processing of input to to get the result of the format string.
  • scanf("%[^\n]%*c", input); fails to read anything when input is "\n". It also lacks a width limit (@chux-ReinstateMonica).
#include <stdio.h>
#include <string.h>

#define MAX_INPUT 81
#define MAX_ARGS 81

int main() {
    for(;;) {
        char input[MAX_INPUT];
        scanf("%[^\n]%*c", input);
        if(!strcmp(input, "Exit")) break;

        int counter = 0;
        char *token;
        char *args[MAX_ARGS];
        do {
            token = strtok(counter ? NULL : input, " ");
            args[counter] = token;
            if(token) counter  ;
        } while(token && counter < MAX_ARGS);
        if(counter == MAX_ARGS) {       
            counter--;
            args[counter] = NULL;
        }

        printf("\nlast string: %s\n", args[counter - 1]);
        for(unsigned i=0; i < counter; i  ) {
            printf("%d %s\n", i, args[i]);
        }
        printf("\n");
    }
    return 0;
}
  •  Tags:  
  • c
  • Related