Here is my function’s code:
char * increment_b_string(char * b_string)
{
char * ret_string = (char *) malloc(7);
ret_string = "001aaa";
if (*(b_string + 2) == '9')
{
*(ret_string +2) == '0';
if (*(b_string + 1) == '9')
{
*(ret_string +1) = '0';
*(ret_string) = *(b_string) + 1;
} else {
*(ret_string + 1) = *(b_string + 1) + 1;
}
} else {
*(ret_string + 2) = *(b_string + 2) + 1;
}
return ret_string;
}
Any thoughts as to why it might be failing?
The general idea is that b_string will contain a value like “123aaa”. The “aaa” portion does not matter, and will never change. Only the first 3 numbers will. They need to increment as though they were integers. Leading zeroes need to be preserved in the beginning. So, if input is “004aaa”, output should be “005aaa”. This only needs to go up to “300aaa”, hence why I’m not considering anything more than that. It’s a school programming assignment, hence the very contrived nature of the problem.
Thanks.
Edit: I’ve changed my function. Here is what it is now.
void increment_b_string(char * b_string)
{
if (b_string[2] == '9')
{
b_string[2] == '0';
if (b_string[1] == '9')
{
b_string[1] = '0';
b_string[0] += 1;
} else {
b_string[1] += 1;
}
} else {
b_string[2] += 1;
}
}
Assuming that b_string is initially populated with…
strcpy(b_string, “001aaa”);
…would this be correct? My program is still exhibiting the same behavior, but this may be an error somewhere else in the code.
You cannot increment or change a string literal – they are read only in C, which is what you’re doing.
Does not do what you think it does, it does not copy the string into the malloced space
ret_stringpoints to, it sets ret_string to point to the string literal “001aaa”. Use this instead: