Cześć!
Potrzebna mi funkcja, która zwraca wskaźnik do n-tego odseparowanego elementu w stringu. Coś tam wyskrobałam, ale nie wiem czy pod koniec nie powinnam reallocować pamięci na którą wskazuje wskaźnik d? bo był malloc na rozmiar całego stringa("cos=tam=elo") a potem przechowywany jest tam tylko kawałeczek("elo"), więc jest to trochę nieładnie?
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
/* pointer to n separated element of string */
char *nstrsep (const char *string, const char *sep, int npart) {
char *token;
char *d = malloc (strlen (string) + 1);
if (d == NULL) return NULL;
strcpy (d,string);
token = strtok(d,sep);
if (npart>0) {
int i;
for(i=0; i<npart; i++)
token = strtok(NULL,"=");
}
strcpy(d,token);
return d;
}
int main(void) {
char *part;
part = nstrsep("cos=tam=elo","=",2);
printf("%s\n",part);
free(part);
return 0;
}