Reputation: 59
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.
Upvotes: 0
Views: 108
Reputation:
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:
And a few issues not fixed:
#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;
}
Upvotes: 2