i have to write a program, in which i have to make pointer to point to the character, where it last occured in a string. For example:
String: Lord of the rings
Character: r
Pointer points to the last 'r' in the string, that is in the word 'rings'.
If there is no such character, than the pointer must return NULL.
I must use void StringSearch(IN String[], IN Ch, OUT Ptr);

i've written the program, but it's not working:

#include <stdio.h>

void StringSearch(char String[], char Ch, char *Ptr);

int main(){
	char String[100], Ch, *Ptr;
	fgets(String, sizeof String, stdin);
	scanf("%c", &Ch);
	StringSearch(String, Ch, *Ptr);	
	printf("%c", *Ptr);
	getchar();
	return 0;
}

void StringSearch(char String[], char Ch, char *Ptr){  
	int i = 0, j;  
	while(String[i]!= '\0'){	
		i++;  
	}  
	for (j = i; j >= 0; j--){  
		if(String[j] == Ch){  
			Ptr = &Ch;  
	                return;
		 }  
	 }  
	 *Ptr = NULL;  
}

i get an error: Run-Time Check Failure #3 - The variable 'Ptr' is being used without being defined on the line StringSearch(String, Ch, *Ptr);

and i don't know how to define it, because NULL must also come from the function and not from main().

Member Avatar for iamthwee

> i have to make pointer to point to the character

Why just return the position as an integer.

>void StringSearch(char String[], char Ch, char *Ptr);
The first rule of simulating pass-by-reference using pointers is that if you want to change the value of an object, you pass a pointer to it. You want to change the value of the pointer, not the character being pointed to, so you need to pass a pointer to the pointer:

void StringSearch(char String[], char Ch, char **Ptr);

Find that you have assigning address of the character which is stored in program stack. This is not valid.... directly copy the address returned by strchr and print it you will get required result

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.