将字符追加到String并返回String

时间:2015-06-03 23:31:12

标签: c arrays string pointers

我正在尝试拨打String,根据特定条件添加字符,更新最长String,然后返回String

我知道,因为我正在更改String(通过添加字符),我无法使用const char* pointer,因此我必须使用char array[]

但我也知道char array[]不能返回,只是指针。所以我对如何更新字符串(作为char array[]),然后将其返回(作为const char* pointer)感到困惑。

 const char* longestWord(char line[])
 {
     int pos = 0;
     char longest[250]; 
     char ch = line[pos];
     int longestLength = 0;
     char current[250];
     int currentLength = 0;

      if(isalpha(ch) || isdigit(ch))
      {
          longest[longestLength] = ch;
          longest[longestLength + 1] = '\0';
          currentLength++;
      }

    pos++;  
 }
 return longest;

2 个答案:

答案 0 :(得分:2)

除非line足够大以容纳所需的数量,否则您将无法以这种方式执行此操作。

这里最直接的解决方案是让参数在堆上,所以用malloc(length_of_str)分配它。在longestWord中,您可以拨打line = realloc(line, new_length),以便为自己留出更多空间。

返回longest将不会像堆栈一样工作,一旦你的方法离开,它将被释放。您也可以通过longest分配malloc()并返回该指针,在这种情况下,一旦您不再需要它,您只需要在返回的指针上调用free()

答案 1 :(得分:0)

只需将数组传递给函数,您就不需要返回任何内容:

void longestWord(char line[], char longest[])
                     //       ^^^^^^^^^^^^^^
相关问题