string - Converting a character pointer to uppercase in C -
i have pointer:
char * name;
it contains string "test:case"
and i'm calling function it, , trying store in structure. however, want capitalize entire string first, doesn't seem work.
void func(char * name) { int i; list * l; l = malloc(sizeof(list)); for(i=0; i< strlen(name); i++) { name[i] = toupper(name[i]); } l->name = name; //call function later free allocated memory }
where list struct has member (char *) named name.
however, seg faults. can't go using non pointers in case. have use pointers , not character arrays, i'm trying use toupper in every value of char pointer, doesn't seem work.
you're getting segfault because original string presumably literal, , it's not modifiable. need make copy of first.
void func(char * name) { list * l; l = malloc(sizeof(list)); name = strdup(name); // make copy of name (char *p = name; *p; p++) { *p = toupper(*p); } l->name = name; }
note when later free l
, you'll first need free l->name
.
Comments
Post a Comment