【问题标题】:C - Can't save string from inside for loopC - 无法从 for 循环内部保存字符串
【发布时间】:2014-06-06 05:04:07
【问题描述】:

我需要将 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);



}

【问题讨论】:

  • 当然tmp 在while 之外是NULL,因为这正是终止循环的条件。而且你不能strcpy 指向一个不指向任何地方的指针。您需要一些存储空间供tmp2 指向。如果您告诉我们您要做什么,我们可以向您展示正确的方法。
  • 在每次迭代期间不会将 tmp 的值写入 tmp2,以 tmp 的最后一个值结束(在它变为 null 之前)吗?
  • 在你的代码中没有任何东西被正确地写入tmp2。你想做什么?
  • 我正在尝试获取 actual_args[0] 中的最后一个令牌。

标签: c scope strcpy strncpy


【解决方案1】:

您的代码的问题是它没有正确使用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 函数,但不建议这样做。

【讨论】:

    【解决方案2】:

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

    // 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);
    

    【讨论】:

      【解决方案3】:

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

      #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;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-10-09
        • 2020-04-04
        • 1970-01-01
        • 1970-01-01
        • 2011-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多