c - Return pointer to a subarray -
let's have function has char array parameter , char* return type. want return pointer subarray of parameter array.
for example : char str[] = "hi billy bob";
i want function return "billy bob";
let's in body of function able index of want subarray start.
char* fun(const char s1[]) { int index = random int; /* char *p = *(s1[index1]); */ return p; } i'm having trouble commented out line.
simply use
const char *p = &str[index]; /* may write p = str + index */ return p; the above takes address of character @ index index -- pointer char array beginning @ index. string continues until first '\0' character end of original str.
in case, if want output "billy bob" (note cannot change capitalization unless modify string or return new one) should set index = 3;.
it gets more involved when want take substring of str. either have set str[end_index]='\0' or use malloc allocate new array , copy relevant part.
some information regarding 2 syntax options
in c, expression a[i] equivalent *(a+i). i.e., take pointer a, move forward i elements (chars in case) , return element @ resulting address.
if prefix a[i] & operator address of character. &a[i] may written &*(a+i). operators '&' , '*' cancel each other , left a+i.
Comments
Post a Comment