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