示例#1
0
int main(void)
{
	//Create Pointers
	char *sentance;
	char *reversesen;
	
	int start = 0;
	
	//Assign Memory to pointers using malloc
	sentance = malloc(100);
	reversesen = malloc(100);

	printf("Enter a sentance: \n");
	fgets(sentance, 100 , stdin); // input string assigned to sentance array
								//stdin represents standard-input from the stdio.h header

	printf("sentance is: %s\n", sentance);

	swap_chars_in_word (sentance, reversesen, start);//function passes variables to be used in function.
	
	printf("reverse is: %s\n", reversesen);//prints the new value

	//free pointers this is used to avoid memory leaks etc
	free(sentance);
	free(reversesen);
	
	return 0;
}
int main(void)
{

/* Initialising variables. */
char *sentence; //string (char array)
int i,length;

sentence = (char*)malloc(100);

printf("Enter a sentence:\n"); //asks for sentence
fgets(sentence, 100, stdin); //user inputs sentence

//setting the \n to be a space instead, makes testing conditions
//easier later when looping through "sentence", only need to test
//for space, not for space OR newline.
length = strlen(sentence);
printf("String Length: %d\n", length);
sentence[length-1] = ' ';

for(i = 0; i < length; i++)//continue until end of string is reached
{
//Tests whether current location is the start of a new word.
//First element is assumed to be start of a word, and if the element
//before the current location is a space, then we are at start of new word.
if ((i==0)||(sentence[i-1] == ' '))
{
//If we are at the start of a word, call function to swap chars,
//passing to it as parameters the string "sentence" and the current
//position in "sentence" where the word begins.
swap_chars_in_word(sentence, i);
}

//continues through string doing nothing until a new word begins.
else{
}

}

//Prints out "sentence" with its words reversed.
printf("%s", sentence);

//release memory allocated and set pointer to NULL
free(sentence);
sentence = NULL;
return 0;
}