what I wanna to do is get space separated words into a 2d array.what I am thinking is replace space by a '\0',so I can copy the string to array.And then add the string pointer to the place after '\0'.keeping do it till the last.But when I done it ,I consider how can I free the pointer.I consider maybe I can save it first so I use char *t = s.But when I free the t I get a segment error.so how should i free the s pointer after it move to another place. beside this,I also have some questions: 1.after I malloc a sizeof(char)*15 memory ,I expect printf strlen(s) I can print 15,but I get 0,why?If I wanna know the size of s now,how should I do? 2.after strcpy str to s,the strlen s become 11.But I malloc size of 15,where will the left memory go? does that effect program?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char buf[10][5];
char *str = "10 8 6 9 76";
char *s;
char *t = s;
s = (char *)malloc(sizeof(char)*15);
printf("strlen 1 s:%d\n",strlen(s));
memset(s,0x00,sizeof(char)*15);
printf("strlen 2 s:%d\n",strlen(s));
strcpy(s,str);
int n = strlen(s);
int i = 0;
int j = 0;
int k = 0;
for( i = 0; i < n; i++ ){
if( s[i] == ' '){
s[i] = '\0';
strcpy( buf[k], s);
s += (i+1);
k++;
n = n - i - 1;
i = 0;
}
}
printf("s:%s\n",s);
strcpy( buf[k], s );
for( j = 0; j<= k; j++ ){
printf("buf[%d]:[%s]\n",j,buf[j]);
}
printf("j:%d\n",j);
free(t);
return 0;
}