I have a string with some spaces on the end. I would like to terminate this string at the position when the first space occurs, so that when I later do strncpy() on it, it would copy only the part of the string which doesn't contain spaces.
This is some try which gives me a segault obviously. How can I do what I intend to do?
int main() { char* s1 = "SomeString "; *(s1 + 10)='\0'; printf("%s\n",s1); return 0; }
puts(strncpy(s2,s1,10));will serve the purpose here.s1points to a string which is allocated in read-only memory segment. Attempting to write into this segment causes a memory-access violation. That being said, you can usestrtokfor your purpose (again, as long as your string is allocated in a writable memory segment).50there. In addition, one good reason for the down-vote might be the fact that you've shown a very "hard-coded" example of how you truncate that string at index10.*(s1 + 10)is by definition equivalent to the more commons1[10]. It is also equivalent to*(10 + s1)and10[s1]interestingly.