Hi, i keep getting a segmentation fault and i cannot figure where the problem is, well the problem is in the while loop but not sure what is wrong with it.
Question is enter a line of words with spaces then tokenize them and print in reverse.
Here is the code:

#include<stdio.h>
#include<string.h>
void main ()
{
	char sentense[100]="\0";
	char tokens[25][20];
	char *sptr;
	int i=0,j=0,t;
	printf ("Enter a line of text:\n", sentense);
	fgets (sentense, 99, stdin);
	//printf ("\n%s", sentense);
	sptr=strtok(sentense, " ");
	strcpy(tokens[i],sptr);
	printf ("%s\n", tokens[i]);
	i=1;
	while (sptr!=NULL)
	{
		sptr=(NULL, " ");
		strcpy(tokens[i],sptr);
		i++;
		//printf ("\n%s", tokens[i]);
	}
	printf ("\n");
	for (t=i-1; t>=0; t--)
	{
		printf ("%s ", tokens[t]);
	}
}

Any help would be appriciated.

The tokens array should be an array of pointers. what will happen if you enter a word with more than 19 characters? Anbswer: buffer overflow. The following will be ok as long as you are not going to change the contents of sentence again, such as use that characte array for something else later on in the program.

line 16: That while loop is wrong

char* tokens[20] = {0}; // an array of pointers
tokens[i++] = strtok(sentence," ");
while( sptr != NULL)
{
  printf("%s\n", tokens[i];
  tokens[i++] = strtok(NULL, " ");
  
}

thanks for a quick reply, i edited the code, but when i had token[i++] kept giving me segmentation error, so i took out and it works for the first round, and then gives me segmentation error again inside the while loop
here is what i ended up with:

#include<stdio.h>
#include<string.h>
void main ()
{
	char sentense[100]="\0";
	char *tokens[20]={0};
	char *sptr;
	int i=0,j=0,t;
	printf ("Enter a line of text:\n", sentense);
	fgets (sentense, 99, stdin);
	tokens[i]=strtok(sentense, " ");
	printf ("%s\n", tokens[i]);
	i++;
	while (tokens!=NULL)
	{
		printf ("%s\n", tokens[i]);
		tokens[i]=strtok(NULL, " ");
		i++;
	}
	printf ("\n");
	for (t=i-1; t>=0; t--)
	{
		printf ("%s ", tokens[t]);
	}
}

When will tokens == NULL? It's the name of an array, it's not the contents of the any element of the array.

line 14 should be while (tokens[i-1]!=NULL)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.