Reputation: 2612
I am trying to pad a certain amount of zeros to the beginning of a char array, which is to be later read as ints. Here is my code:
// charArray is '123' right now
// want charArray to be 00123
// Shift elements in array forward 'difference' times
// difference is amount of 0s to be padded to beginning of string, difference = 2 here
for (i = strlen(charArray) - 1; i >= 0; i--) {
charArray[i+difference] = charArray[i];
}
This is where I have problems. The way the code below runs, charArray
is ??123
for (i = 0; i < difference; i++) {
y[i] = 0 - '0';
}
If I do this instead:
for (i = 0; i < difference; i++) {
y[i] = 0;
}
My string gets terminated early. Any ideas?
Upvotes: 0
Views: 4557
Reputation: 849
So the problem is the character you are setting. In the first case you use y[i] = 0 - '0';
which will give you a character value of -48, which will be a byte of hex 0xD0. This is a character in the extended ascii range which is why you are getting a peculiar character there.
In the second case you used y[i] = 0;
Which is a byte value of zero which is used as a zero terminator (hence the early termination of your string).
What you want to use is y[i] = '0';
Upvotes: 0
Reputation: 104589
If your originally allocated array is big enough to hold both the original string, it's null terminator, and the padding together, then you can do this:
memmove(charArray+difference, charArray, strlen(charArray));
memset(charArray, '\0', difference);
If you are shifting a string that doesn't have the extra allocate bytes, then some characters are going to get dropped. Hence:
Shift a string by N "difference" bytes and pad the leading space with zeros
int original_array_size = strlen(charArray) + 1;
memmove(charArray+difference, charArray, original_array_size-difference);
memset(charArray, '\0', difference);
charArray[original_array_size - 1] = '\0'; // assumes original_array_size is >= 1
Upvotes: 0
Reputation: 145317
To set the padding area, just use this code:
for (i = 0; i < difference; i++) {
charArray[i] = '0';
}
or possibly:
memset(charArray, '0', difference);
Upvotes: 1