removing white space from char* array

Im writing a function that wil remove white empty space in a array of char

i am getting an error saying :

Access violation writing location

my logic seems fine but i cant even check it without being able to send my char pointer withSpaces over to my new char pointer output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
char* StripSpaces(char* input)
{
    char* output = input;
    int i = 0, j = 0;
        
    while (input[i] != '\0')
    {
        if (input[i] != ' ')
	{
		output[j] = input[i];
	}
	else
		j--;

	i++; j++;
    }

    return output;	
}

int main()
{
    char* withSpaces = "Oh My Word!";

	char* stripped = StripSpaces(withSpaces);

	printf("6) STRIP SPACES\n%s => %s\n\n", withSpaces, stripped);

	std::cout << std::endl;
	system("pause");
	return 0;
}
}
Line 23: "Oh My Word" is actually a const char * and is stored by the compiler in your code space (read only). A good compiler should have thrown at least a warning on this line that you're trying to change the const-ness of the string.

Line 3: You equate output to input which means you now have a writable pointer pointing to your read-only string.

Line 10: When you try to write to output, you're going to get a segmentation fault (access violation) because you're trying to write to read-only memory.

edit:
Line 26: When you fall out of the while loop, you don't terminate the modified string.
Last edited on
@ OP: You do understand that at Line 3 you are only copying the address held by 'input' into 'output' right? You are not actually copying the contents of the memory that it points to. What you probably want, assuming you can't just use std::string like any sane person would, is the "memcpy()" function from the 'cstring' header: http://www.cplusplus.com/reference/cstring/memcpy/?kw=memcpy

Lines 27, 29: You are writing to both stdout and cout. They are separate. More inconsistent than an error.

Pointer is a variable that holds one value; an address.

Array is a continuous block of memory that contains multiple values.
1
2
const char * pc = "Oh My Word!";
char ac[] = "Oh My Word!";

The pc has the address of a const string literal.
The ac is initialized by copying characters from constant string literal to it.


Note, your StripSpaces operates inplace. It modifies array pointed to by input. Therefore, after line 25 stripped and withSpaces point to same array.
absolutely perfect explanation of what i was doing wrong!

Thank you so much. No more writing onto memory addresses! :)

switched output to a normal char array and it works just fine!

Thank you!
Topic archived. No new replies allowed.