0
char *placeDelimiter(char message[], int maxSize) {
int msgSize = strlen(message); //length of message
int delSize = (msgSize/maxSize);//how many delimiters are needed
int remSize = msgSize%maxSize; //remainder characters
int newSize = msgSize+delSize; //new size of message
if (remSize==0) delSize--; //if there are no remainders remove , from end
char *temp = (char *)malloc(newSize+1);
int delPos = 0;
int spacing = 0;
for (int x=0;x<msgSize;x++) {
if (delPos==maxSize) {
temp[x] = ',';
delPos=0;spacing++;
} else {delPos++;}
temp[x+spacing] = message[x];
printf("Char: %c DelPos: %d Spacing: %d\n", temp[x], delPos, spacing);
}
temp[msgSize] = '\0';
return temp;
}
上面是放置一個定界符的每設定數(maxSize
)字符陣列意外空字符
當功能可按在輸入與4
沿給定如"This is a message"
爲maxSize
則輸出的功能應該是"This, is ,a me,ssag,e"
。然而,在循環過程中出現空字符的問題明顯充當字符數組的結尾
我在循環中的printf中添加了以提供更多信息,這是給出的輸出:
Char: T DelPos: 1 Spacing: 0
Char: h DelPos: 2 Spacing: 0
Char: i DelPos: 3 Spacing: 0
Char: s DelPos: 4 Spacing: 0
Char: , DelPos: 0 Spacing: 1
Char: DelPos: 1 Spacing: 1
Char: i DelPos: 2 Spacing: 1
Char: s DelPos: 3 Spacing: 1
Char: DelPos: 4 Spacing: 1
Char: , DelPos: 0 Spacing: 2
Char: DelPos: 1 Spacing: 2
Char: DelPos: 2 Spacing: 2
Char: m DelPos: 3 Spacing: 2
Char: e DelPos: 4 Spacing: 2
Char: , DelPos: 0 Spacing: 3
Char: s DelPos: 1 Spacing: 3
Char: DelPos: 2 Spacing: 3
This, is ,
第二個逗號後面的字符爲空,我找不到原因。有沒有人有任何想法爲什麼?
嗯,你上次'臨時[msgSize] = '\ 0';'應該be' temp [msgSize + spacing] ='\ 0';',但我不確定是否證明結果正確。 – rodrigo
@rodrigo間距是爲了證明逗號,而msgSize意味着已經考慮到了這一點 –
'msgSize'設置爲'strlen(消息)'並且永不再修改。寫入'temp'的最後一個有效字符是'temp [x + spacing]'並且在最後一次迭代'x == msgSize-1'中,所以'temp'的倒數第二個字符必須是'msgSize + spacing '(或'newSize'也許?),那就是NUL字符應該是的位置。 – rodrigo