I have a program that will form a new sequence (sequence piece) of numbers based on a couple conditions.
I need to print the new sequence formed in the function called Concat
in the main function but also need the Concat
to return 1 so it is known in the main function that the sequence to be printed is valid.
here is my code:
#define BUFFER 50
int Concat(char sequence[], char piece[]){
int sequenceValid = 1;
int sizeSequence = strlen(sequence);
if(sequence[sizeSequence-1] == piece[0]){
sequence = strcat(sequence,piece);
} else if(sequence[0] == piece[1]){
sequence = strcat(piece,sequence);
} else {
sequenceValid = 0;
}
return sequenceValid;
}
int main()
{
char piece[BUFFER], sequence[BUFFER];
scanf("%s", sequence);
scanf("%s", piece);
if (Concat(sequence, piece)){
printf("%s", sequence); // at this stage the new sequence formed above by the method `strcat` should be printed ( sequence piece) not just the sequence, however only the sequence is printed.
}
else{
printf("piece %s cannot be added %s.",piece, sequence);
}
}
As per my note above, if the Concat
function returns true(1) it is printing only the sequence as given by the user and not the sequence piece which is what I want.
Test example: Input:
166335 21
Desired output: 21166335
Current output (errored): 166335
How to print the new sequence in the main function?
CodePudding user response:
There's three things you need to remember when it comes to function arguments in C:
The first is that an argument like
char sequence[]
is really treated aschar *sequence
, that is it's a pointer.The second thing is that all arguments are really local variables to the functions, and their life-time ends when the function ends.
The third thing is that all arguments are passed by value, which means the value at the site of the call is copied into the functions local argument variable.
All put together, all assignments you make to sequence
will be lost once the function returns.
Simple solution: Return sequence
at the end (or a null pointer on invalid sequence).