2013-03-08 24 views
-1

我已經寫了這個函數,用於從右到右傳輸從源字符串到目標字符串的字符數。我傳遞字符串到src,NULL到dst和計數值功能函數用於將字符串中的字符數從右到左傳輸到目標字符串

如果我發送輸入字符串作爲「堆棧溢出」,並計爲4我想o/p字符串作爲「流量」。但是在這裏,我的o/p字符串總是空的,可以用我的邏輯告訴我什麼是錯的。請

char *Rprint(const char *src, char *dst, int count) 
{ 
    int i = 0; 
    char *ret = NULL; 
    while(*src!= '\0') 
     src++; 
    dst = malloc(sizeof(char) * (count + 1)); 
    ret = dst; 
    dst = dst + (count + 1); 
    while(count) 
    { 
     *dst++ = *src--; 
     count--; 
    } 
    *dst++ = '\0'; 
    //return ret; 
    printf("String:%s \n", ret); 

} 
+0

您設置了'dst'一個超過alloc'd緩衝區的末尾,然後遞增...!這是不好的... – 2013-03-08 01:29:00

回答

0

我希望你的意思是這樣:

*dst-- = *src--; 

我不喜歡你這樣做的方式,但應該讓您的軌道上沒有我建議你完全重寫你的碼。

因爲您已經複製了終止符,所以以後不應該空字符結束字符串。您正在將字符串從末尾複製到開頭(,即反向複製),但將其與更常用的正向複製混淆。

小心你的循環條件。您可能會在那裏發生錯誤的錯誤。與將count+1添加到dst一樣。我認爲你應該只添加count

哦,不要忘記從你的函數中返回一個值!

+0

我在while循環中我* dst-- = * src--並且在進入while循環之前,我做了dst = dst + count +1;並且* dst ='\ 0'最初本身我正在注意用'\ 0'來結束刺,但是我仍然只是得到一個空白的o/p – user1985641 2013-03-08 01:56:26

+0

編號'src'已經坐在''\ 0'性格。這將是第一個被複制的。它應該進入'dst + count',* not *'dst + count + 1'。 – paddy 2013-03-08 01:58:09

+0

對不起,我明白你告訴我,因爲我不需要NULL終止字符串,即使做了我仍然無法得到任何O/P – user1985641 2013-03-08 02:02:56

0

下面是工作代碼,基於您的原始方法,但幾乎沒有更正。

#include <stdio.h> 

void Rprint(const char [], char [], int); 


int main() 
{ 
char buff[50] = "stack overflow"; 
char cut [50]; 

Rprint(buff,cut,5); 
puts(cut); 
} 


void Rprint(const char src[], char dst[], int count) 
{ 

    while(*src!= '\0') 
     src++; 

    src = src - count; 

    while(count--) 
     *(dst++) = *(src++); 

    *(dst++) = '\0'; 

} 
相關問題