Null-terminating a string in C -


i have string spaces on end. terminate string @ position when first space occurs, when later strncpy() on it, copy part of string doesn't contain spaces.

this try gives me segault obviously. how can intend do?

int main() {     char* s1 = "somestring             ";     *(s1 + 10)='\0';     printf("%s\n",s1);      return 0; } 

you're attempting modify string read because of way declared pointing constant value. you'll have make copy first:

#include <stdio.h> #include <string.h>  int main() {     char* s1 = "somestring             ";     char *s2 = strdup(s1);     char *s3 = strchr(s2, ' ');     *s3 = '\0';     printf("%s\n",s2);     /* if not needed more, because strdup allocates heap memory */     free(s2);      return 0; } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -