A
ajinkya.coep
What's wrong with this program? If you were to fix it, what would the
intended output be?
void swap(char *str, int index1, int index2) {
char tmp = str[index1];
str[index1] = str[index2];
str[index2] = tmp;
}
int main(int argc, char *argv[]) {
char *planet1;
char *planet2;
planet1 = (char *) malloc(7 * sizeof(char));
if (!planet1)
return 0;
snprintf(planet1, 7, "Jupiter");
planet2 = "Saturn";
swap(planet1, 0, 3);
swap(planet2, 3, 4);
printf("results: %s and %s\n", planet1, planet2);
return 0;
}
My interpretation : In turboc3 compiler(though it is a dead compiler
now) this problem is perfectly fine and we
get the o/p :
results: iupJter and Satrun
But in Bloodshed Dev C++ the code compiles fine but on
execution there is an error report generated.
swap(planet1,0,3) works fine but there is some problem
with swap(planet2,3,4)
Only when i allocate space for planet2 and perform
snprintf on planet2 i get the expected result.
Why do we need snprintf in this case....why does
planet2="Saturn" not work?
PS
ls send your comments and correct me if i am wrong...i am working
on this problem for 2 long days.
intended output be?
void swap(char *str, int index1, int index2) {
char tmp = str[index1];
str[index1] = str[index2];
str[index2] = tmp;
}
int main(int argc, char *argv[]) {
char *planet1;
char *planet2;
planet1 = (char *) malloc(7 * sizeof(char));
if (!planet1)
return 0;
snprintf(planet1, 7, "Jupiter");
planet2 = "Saturn";
swap(planet1, 0, 3);
swap(planet2, 3, 4);
printf("results: %s and %s\n", planet1, planet2);
return 0;
}
My interpretation : In turboc3 compiler(though it is a dead compiler
now) this problem is perfectly fine and we
get the o/p :
results: iupJter and Satrun
But in Bloodshed Dev C++ the code compiles fine but on
execution there is an error report generated.
swap(planet1,0,3) works fine but there is some problem
with swap(planet2,3,4)
Only when i allocate space for planet2 and perform
snprintf on planet2 i get the expected result.
Why do we need snprintf in this case....why does
planet2="Saturn" not work?
PS
on this problem for 2 long days.