'I am trying to add two strings together but getting 3221225477 Error
I am trying to get a number and a repetition number then adding as many numbers as the number of repetition one after the other. But I am getting 3221225477 result. What should I do?
The function:
char *repetitor(char number[], int repFactor){
char* temp;
while(repFactor>0){
strcat(temp, number);
repFactor--;
}
return temp;
The main function:
int main(int argc, char *argv[]) {
char* number;
int repFactor = 0;
printf("Please enter a number (n=) :");
scanf("%s", &number);
printf("Please enter repetition factor (k=) :");
scanf("%d", &repFactor);
char* numberRep = (repetitor(number,repFactor));
Solution 1:[1]
Lots of issues here:
scanf("%s", &number); reads stdin and stores input in a buffer pointed to by the second argument. number is not the expected buffer, it's a pointer, so you're passing the address of a pointer (char **) to scanf(). number is sizeof(char *) bytes big, so you can get away with entering a character or three, but number should be an array of characters:
char number[100]; … scanf("%s", number); // no check for overflow!
Re: repetitor(), not only is temp uninitialized (you're copying to random space and strcat() needs find a trailing NUL), there's no buffer space allocated, and you're returning a stack variable that no longer exists when repetitor() returns.
When you're learning, turn on ALL your compiler warnings.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul Lynch |
