C - 无法从内部保存字符串for循环

时间:2014-04-22 02:04:40

标签: c scope strcpy strncpy

我需要将tmp的内容保存到tmp2。但是,在while循环之外,tmp始终为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);



}

3 个答案:

答案 0 :(得分: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功能,但不建议这样做。

答案 1 :(得分: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);

答案 2 :(得分: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;
}