Enayet Hussain
Enayet Hussain

Reputation: 1018

Char array unexpected null character

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;
}

The above is a function that places a delimiter every set number of characters (maxSize)

When the funciton is given in input such as "This is a message" along with 4 for maxSize then the output should be "This, is ,a me,ssag,e". However there is an issue which is giving null characters during the loop of which obviously acts as the end of the character array

I added in the printf in the loop to provide more information during the process and this is the output given:

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 ,

The character after the second comma is null and I can not find a reason for it. Does any one have any ideas why?

Upvotes: 0

Views: 132

Answers (1)

rodrigo
rodrigo

Reputation: 98368

There are two problems with this code. One

temp[x] = ',';

should be:

temp[x + spacing] = ',';

because that is where the character would be if the condition is false.

And two, is the NUL I talked in the comments:

temp[msgSize] = '\0';

should be:

temp[msgSize + spacing] = '\0';

IMO, it would be easier to understand if you used two index variables instead of an offset. Something like:

for (x = 0, y = 0; x < msgSize; ++x, ++y)
{
    if (...)
      temp[y++] = ',';
    temp[y] = message[x]; 
}
temp[y] = '\0';

PS: You should try and use a debugger, it makes some things easier...

Upvotes: 1

Related Questions