在我的 C 程序中,我使用 strtok()
命令循环遍历字符串
中的所有标记。在每次迭代中,它都会给我一个指向每个标记的指针。
如何将指针存储在数组中,以便该数组就像 main 函数中的 argv 参数一样,并且可以在 execvp 命令中使用?
最佳答案
如果您知道要获得多少个托克,则可以通过创建指向字符串的指针 vector 来实现这一点。否则,您将需要使用动态结构。
如果您知道大小,则可以使用以下方法:
char **mytokens = malloc(MAXSIZE*sizeof(char*)); /*Allocation of a vector of pointers to strings*/
while(there_are_tokens && counter < MAXSIZE){
mytokens[counter] = strtok(NULL,mystring); /*Assuming you did strtok with delims before*/
counter++;
}
但是像这样的结构将是我这样做的方式:
typedef struct _tokens{
char *token;
struct _tokens *next;
}tokens;
希望这有帮助。
关于c - 如何创建指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14404132/