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

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -