2016-07-10 180 views
2

所以我試圖將兩個字符串結合在一起,但我得到str是第二個while循環的最後一行的只讀值。他們是否可以在不更改函數頭的情況下做到這一點?通過從結構的字符指針遍歷

另外String是我創建的一個struct,它有一個名爲str的* char。

String * String_Combine(String * tar, const String * src) { 
//end of string 
    while (* tar->str != '\0') { 
    tar->str++; 
    } 
//int i = 0; 
//copy string 
    while (*source->str != '\0') { 
    *tar->str = *src->str; 
    *tar->str++; 
    *src->str++; 
    // i++; 

    } 
return tar; 
} 
+1

什麼是'source'? – MikeCAT

+0

這段代碼有足夠的錯誤,我建議將其全部廢棄並從頭開始重新寫入。 – Hurkyl

+0

從'tar-> str ++'和'src-> str ++'中刪除'*'。你應該得到一個警告,說明「計算未使用的值」或類似的東西。 –

回答

2

在修改指針前複製指針。我想修改tar->str也可能是有害的,因爲它會破壞字符串開始的信息。

String * String_Combine(String * tar, const String * src) { 
    char * tar_str = tar->str, * src_str = src->str; 
    //end of string 
    while (* tar_str != '\0') { 
    tar_str++; 
    } 
    //int i = 0; 
    //copy string 
    while (*src_str != '\0') { /* assuming that "source" is a typo and it should be "src" */ 
    *tar_str = *src_str; /* with hope that there is enough writable buffer allocated */ 
    tar_str++; 
    src_str++; 
    // i++; 

    } 
    //terminate string 
    *tar_str = '\0'; 
    return tar; 
} 
+0

我不得不刪除行* tar_str ='\ 0';'但它工作正常。 –

0

兩件事情:

  1. 確保分配足夠的內存來焦油> strto同時按住焦油> STR和SRC-> STR
  2. 存儲指針焦油/ SRC-> STR在本地和迭代思想他們,所以你不會失去原始str的指針;

我寫了一個測試案例,您可以輕鬆瞭解它;)

#include <iostream> 
#include <string.h> 
struct String { 
    char* str; 
}; 
using namespace std; 
String * String_Combine(String * tar, const String * src) { 
// take a local copy of strs 
char* tar_str = tar->str; 
char* src_str = src->str; 
//end of string 
while (* tar_str != '\0') { 
    tar_str++; 
} 

//int i = 0; 
//copy src string to tar string 
    while (*src_str != '\0') { 
    *tar_str = *src_str; 
    *tar_str++; 
    *src_str++; 
    // i++; 

    } 
return tar; 
} 
int main() 
{ 
    String* src = (String*) malloc(sizeof(String)); 
    src->str = new char[20]; 
    strcpy(src->str, "World!"); 

    String* tar = (String*) malloc(sizeof(String)); 
    tar->str = new char[20]; 
    strcpy(tar->str, "Hello "); 
    String* result = String_Combine(tar,src); 

    cout << result->str << endl; 

    return 0; 
}