簡體   English   中英

C中的此串聯函數有什么問題?

[英]What is wrong with this concatenation function in C?

這是使用結構的作業分配的一部分,我似乎無法理解這一功能。 該函數為string_t * concat(string_t * s1,string_t * s2),它返回新的字符串結構。 到目前為止,這就是我所擁有的,只要到達編譯器,它就會崩潰。 程序已編譯,但是執行時出現“ file” .exe停止工作錯誤。 任何幫助將不勝感激。 謝謝!

typedef struct string{ //String struct (in .h file)

char *line;
int length;

} string_t;


string_t* concat(string_t *s1, string_t *s2) { //actual function (in .c)

int len1, len2;
len1 = length(s1);
len2 = length(s2);

int i, j, s;

string_t *newStr;
newStr = (string_t*)malloc(sizeof(string_t)*2);


for (i = 0; i<len1; i++) {
    *((newStr->line)+i) = *((s1->line)+i);
    }

for (j=0; j<len2; j++) {
    *((newStr->line)+(i+j)) = *((s2->line)+j);
    }

*((newStr->line)+(i+j))='\0';

return newStr;

}



concat(s1, s2); //tests function
newStr = (string_t*)malloc(sizeof(string_t)*2);

您為newStr分配了內存,但沒有為newStr->line分配內存。 嘗試類似:

newStr = malloc(sizeof *newStr);
newStr->line = malloc(s1->length + s2->length + 1);

旁注: *((newStr->line)+i)可以寫為newStr->line[i]

順便說一句,這是一種無需使用丑陋的ptr數學語法的方法:

char* dest = newStr->line;

const char* src = s1->line;
while (*src)
{
  *dest = *src;
  ++dest;
  ++src;
}

src = s2->line;
while (*src)
{
  *dest = *src;
  ++dest;
  ++src;
}

*dest = '\0';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM