或者更确切地说,strtok如何生成它的返回值指向的字符串?它是否动态分配内存?我问,因为我不确定是否需要在以下代码中释放令牌:
STANDARD_INPUT变量用于退出过程,以防我内存耗尽以进行分配,字符串是测试对象.
int ValidTotal(STANDARD_INPUT, char *str)
{
char *cutout = NULL, *temp, delim = '#';
int i = 0; //Checks the number of ladders in a string, 3 is the required number
temp = (char*)calloc(strlen(str),sizeof(char));
if(NULL == temp)
Pexit(STANDARD_C); //Exit function, frees the memory given in STANDARD_INPUT(STANDARD_C is defined as the names given in STANDARD_INPUT)
strcpy(temp,str);//Do not want to touch the actual string, so copying it
cutout = strtok(temp,&delim);//Here is the lynchpin -
while(NULL != cutout)
{
if(cutout[strlen(cutout) - 1] == '_')
cutout[strlen(cutout) - 1] = '\0'; \\cutout the _ at the end of a token
if(Valid(cutout,i++) == INVALID) //Checks validity for substring, INVALID is -1
return INVALID;
cutout = strtok(NULL,&delim);
strcpy(cutout,cutout + 1); //cutout the _ at the beginning of a token
}
free(temp);
return VALID; // VALID is 1
}
Run Code Online (Sandbox Code Playgroud)
And*_*eas 10
strtok操纵您传入的字符串并返回指向它的指针,因此不会分配任何内存.
请考虑使用strsep或至少strtok_r来节省一些令人头疼的问题.
strtok(...) 函数的第一个参数是你的字符串:
str
要截断的 C 字符串。请注意,此字符串通过分解为更小的字符串(标记)进行了修改。或者,可以指定空指针,在这种情况下,函数会继续扫描先前成功调用函数的位置。
它将 '\0' 字符放入您的字符串中,并将它们作为终止字符串返回。 是的,它会破坏您的原始字符串。如果以后需要,请复制一份。
此外,它不应该是一个常量字符串(例如,char* myStr = "constant string";). 参见这里.
它可以在本地分配,也可以通过 malloc/calloc 分配。
如果您在堆栈上本地分配它(例如char myStr[100];),则不必释放它。
如果您通过 malloc(例如char* myStr = malloc(100*sizeof(char));)分配它,则需要释放它。
一些示例代码:
#include <string.h>
#include <stdio.h>
int main()
{
const char str[80] = "This is an example string.";
const char s[2] = " ";
char *token;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL )
{
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
}
Run Code Online (Sandbox Code Playgroud)
注意:这个例子展示了你如何遍历字符串......因为你的原始字符串被破坏了,strtok(...) 会记住你上次的位置并继续处理字符串。
| 归档时间: |
|
| 查看次数: |
12745 次 |
| 最近记录: |