1

我需要将 tmp 的内容保存到 tmp2。但是 tmp 在 while 循环之外始终为 NULL。

if(1){

        char* tmp;
        char* tmp2;

        // split the string on the space character
        tmp = strtok(actual_args[0], " ");

        while(tmp != NULL){
            strcpy(tmp2, tmp);
            tmp = strtok(NULL, " ");                
        }


        // always NULL
        printf("%s", tmp);

        // produces seg. fault
        printf("%s", tmp2);



}
4

3 回答 3

0

您的代码的问题在于它没有strcpy正确使用:该函数复制字符串的内容,它不会创建字符串内存的副本。

为目标字符串分配内存是您的任务。您可以在自动内存(即堆栈)、静态内存或动态内存(即堆)中执行此操作。

如果你想为你的字符串分配动态内存,你可以这样做:

char tmp2 = NULL; // Don't forget to initialize tmp2
...
while(tmp != NULL){
    free(tmp2);                   // Free the old content of tmp2
    tmp2 = malloc(strlen(tmp)+1); // Add one byte for null terminator
    strcpy(tmp2, tmp);            // Now the copy has space to which the data is copied
    tmp = strtok(NULL, " ");                
}
... // Use tmp2 ...
free(tmp2); // You need to free dynamically allocated memory

您也可以为此使用非标准strdup函数,但不建议这样做。

于 2014-04-22T02:12:49.043 回答
0

如果您的目标是找到最后一个令牌:

// assuming actual_args[0] is a char *
char *lastToken = actual_args[0];
for (int i = 0; 0 != actual_args[0][i]; i++) {
    if (' ' == actual_args[0][i]) lastToken = &actual_args[0][i+1];
}

printf("%s", actual_args[0]);
printf("%s", lastToken);
于 2014-04-22T02:18:32.900 回答
0

如果你想要一个包含所有标记的数组,你可以这样做:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_TOKS 10

int main() {
  char *p, *toks[MAX_TOKS];
  char str[] = "a string to tokenize";
  int i, n = 0;

  p = strtok(str, " ");
  while (p) {
    if (n >= MAX_TOKS) {
      fprintf(stderr, "MAX_TOKS overflow\n");
      exit(EXIT_FAILURE);
    }
    toks[n++] = p;
    p = strtok(NULL, " ");
  }

  for (i = 0; i < n; ++i)
    printf("[%s]\n", toks[i]);

  return 0;
}
于 2014-04-22T02:19:29.413 回答