puts() not printing out string in main() but prints fine in function
#include <stdio.h>
#include <string.h>
void mergeStr(char *a, char *b, char *c);
int main()
{
char a[80],b[80];
char c[80];
printf("Enter the first string: n");
gets(a);
printf("Enter the second string: n");
gets(b);
mergeStr(a,b,c);
printf("mergeStr(): ");
puts(c);
return 0;
}
void mergeStr(char *a, char *b, char *c)
{
int size; int i ; int j=0 ; // again, forgot to initialize j
char ch;
char temp[80] ;
/* Merge string a and string b together, then sort them alphabetically */
c = strcat(a,b) ;
size = strlen(c) ;
for (ch = 'A' ; ch <= 'z' ; ch++ ) { // iterates from A-Z and a-z
for (i=0 ; i<size ; i++) { // which for loop comes first is important, in this case since we want duplicates we should allow i to iterate everything for every case of ch
if (c[i] == ch){
temp[j] = c[i] ;
j++ ;
}
}
}
for (i=0 ; i<size ; i++) {
c[i] = temp[i] ; // assign sorted string back to c
c[size] = ' ' ;
}
// puts(c) <- when puts() is run here, desired output is given
}
In this program, the function takes char a , concatenates it with char b, which is assigned to c.
char c is then sorted and printed out in the main function by puts(c).
For example,
Enter the first string:
afkm
Enter the second string:
bbbggg
abbbfgggkm
mergeStr():
This is the output i get when puts(c) is run from within void mergeStr() function.
However, puts(c) from int main() does not print anything.
This:
/* Merge string a and string b together, then sort them alphabetically */
c = strcat(a,b) ;
doesn't do what you seem to expect, it doesn't write into the caller's (ie main()
's) buffer at all. It overwrites the value of c
(the function argument) with the return value of strcat()
, which will be the destination, ie a
.
You need to read up on how C strings work, and how the memory holding them is handled.
That particular call could be replaced by:
sprintf(c, "%s%s", a, b);
but this is dangerous and risks overwriting buffers since no size information is passed into the function (so it can't use snprintf()
).
上一篇: 为什么Java主要方法是静态的?