Can anyone please help me? I need to remove the first character from a char *
in C.
For example, char * contents
contains a '\n'
character as the first character in the array. I need to detect and eliminate this character, modifying the original variable after its been "sanitized".
Can anyone help me with the code? I'm completely new to C, and just can't seem to figure it out.
It sounds as if you're under the impression that a char* "contains" characters. It does not. It merely points at a byte. The rest of the string is implied to consist of the subsequent byte in memory up until the next null byte. (You should also be aware that although the 'char' data type is a byte, by definition, it is not really a character - please be aware of Unicode - and nor is a byte necessarily an octet.)
The char* is not an array, either, although there may exist an array of characters such that the pointer is pointing to the beginning of that array.
char* contents_chopped = contents + 1;
This will result in
contents_chopped
pointing to the same string, except the first char will be the next after \nAlso, this method is faster.
Here is my code
}
Or, if the pointer can be modified:
Do not just increment the pointer if you have malloc'd any memory or your program will crash. free needs the original pointer. You can copy the pointer, make a new chunk of memory and memcpy it, access it as ptr+1 or any of a bunch of other ways, but the people who say just increment the pointer are giving you dangerous advice. You can run this sample program and see what happens when you "just increment the pointer".
Hint: Here's the result: