Here is my code, when i return "fo", the result is "0x7fffffffd870 "fo" ", my question is how to make it return "fo"?
#include <stdio.h>
#include <string.h>
#include <regex.h>
char *substr(char *s, int from, int to) {
int n = to - from + 1;
char subs[n];
strncpy(subs, s + from, n);
return subs;
}
int main(int argc, char **argv) {
char *s = substr("foo", 0, 1);
puts(s);
return (0);
};
update, here is correct code, but I don't know what's diff between char subs[n]
and char* subs=malloc(n)
char *substr(char *s, int from, int to) {
int n = to - from + 1;
char *subs = malloc(n);
strncpy(subs, s + from, n);
return subs;
}
int main(int argc, char **argv) {
char *s = substr("foo", 0, 1);
puts(s);
return (0);
};