It would appear that the memory space on which the string is stored is not modifiable. But that's not expert opinion, rather just from empirical testing. Can't memset the location, so therefore it's not modifiable. And strtok modifies the string you pass it.
You can just make test as an array.
asrockw7
Junior Poster in Training
56 posts since Apr 2011
Reputation Points: 10
Solved Threads: 3
You just need to have it on real allocated memory. If you really want a pointer then strcpy it to a calloc'd pointer.
asrockw7
Junior Poster in Training
56 posts since Apr 2011
Reputation Points: 10
Solved Threads: 3
It would appear that the memory space on which the string is stored is not modifiable.
Correct. String literals are defined as read-only by the language, and strtok() modifies its argument.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
i donot know what to do can u explain me by the help of code please.
You have no choice but to make sure the source string passed to strtok() is modifiable. That means either storing it initially in an array:
#include <stdio.h>
#include <string.h>
int main(void)
{
char src[] = "asim.nazeer.helo.me";
char *tok = strtok(src, ".");
while (tok != NULL) {
printf("'%s'\n", tok);
tok = strtok(NULL, ".");
}
return 0;
}
Or making a copy if you don't control the string provided or need to retain the original string for any reason:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void foo(const char *s) // Assuming no control over s
{
char *copy = malloc(strlen(s) + 1);
char *tok;
if (copy == NULL)
return;
strcpy(copy, s);
for (tok = strtok(copy, "."); tok != NULL; tok = strtok(NULL, "."))
printf("'%s'\n", tok);
}
int main(void)
{
char *src = "asim.nazeer.helo.me";
foo(src);
return 0;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401