Purpose of the program:
This program is supposed to use a void function called removeLetters to remove both uppercase and lowercase letters from a given string. The function isn't allowed to use square brakets (ie no arrays) and the only (1) local variable allowed must be a pointer.


Problem:
The code below compiles fine, and to me it looks and feels like a logical solution, but when compiled using VS, the program crashes, and on XCode, GDB returns a EXC_BAD_ACCESS signal when executing the line:

*hold = *(hold + 1);

saying it's some sort of memory permissions problem. Any help would be greatly appreciated, thanks! I'd also prefer if I didn't just get slapped with code in return, but have someone explain what's going on here.

Full program code below.

void removeLetters(char* str) {
	
	char* hold=str;
	
	while(*str != '\0') {
		
		if ((*str <= 'Z' && *str >= 'A') || (*str <= 'z' && *str >= 'a')) {
			
			hold = str;
			while (*(hold+1) != '\0') {
				*hold = *(hold+1);
				hold++;
				
			}
			*hold = '\0';
			
		} else {
			
			str++;
			
		}
		
	}
	
}

int main() {
	char* string = "123456gfffdal";
	removeLetters(string);
	return 0;
}

Now I might be wrong about this, but I think your char* in main is pointing to where the literal string is in the code. It is not allocating space on the stack for a variable.

Your function is then attempting to change the code, which it's not allowed to.

If you change your string declaration to

char string[] = "123456gfffdal";
	removeLetters(string);

It works fine.

Your problem statement says the function can't use [], it does not seem to pose such a limit on main's declaration of the string.

In a debugger, you can see that your version and mine above allocate very different memory addresses for the char* that points to the string content.

Aha that does work indeed. I get it now! char* would become a pointer, whereas using just char string[] would be a literal.


Thanks a billion

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.