Returning an array element from an array created within the function in C? -


is proper thing in c ?

char *func1() {     char *str[3] = { "so", "is", "amazing" };       return str[1];  } 

the char *func1() returns pointer, pointing location in memory string stored. when func1() returns won't str array go out of scope , not returning pointer object not exist? dangling pointer (is right name?)

so have 2 solutions make str global never goes out of scope , pointer pointer valid memory address, seems dirty.

the other solutions

char *func2() {     char *str[3] = { "so", "is", "amazing" };     int str1len = strlen(str[1]);      char *ret = (char *)malloc(str1len) ; // create block of mem hold str[1].      strncpy(ret, str[1], str1len);     return ret;  } 

is correct ? proper way func1() or func2()? or there better way?

i have been using func1() time , has not created problems me, mean func1() doing right thing? , func2() unnecessary?

in first function, there no problem returning str[1] not pointing local variable, pointer string literal. note string literals should declared const:

const char *func1(void) {     const char *str[3] = { "so", "is", "amazing" };     return str[1];  } 

your second function returns pointer allocated space. pointer need freed @ point. allocation incorrect, should allocate 1 byte final '\0'. can use strcpy copy string allocated space, or use strdup() both:

char *func2(void) {     const char *str[3] = { "so", "is", "amazing" };     int size = strlen(str[1]) + 1;      char *ret = malloc(size);     return strcpy(ret, str[1]); } 

or simply:

char *func2(void) {     const char *str[3] = { "so", "is", "amazing" };     return strdup(str[1]); } 

never use strncpy, not think does. error prone both programmer , whoever read code.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -