Get exception error in C when trying to loop array - c

//Program Written By: Andre Chitsaz-zadeh
//Program Written On: 10/7/12
//Program calculates book cost for multiple book orders. Program written using multiple functions.`
#include <stdio.h>
#define SIZE 5
void inputData();
int main ()
{
inputData();
}
void inputData()
{
int i = 0;
int costs[5];
printf( "\nPlease enter five products costs.\n" );
while(i < 5)
{
scanf("%d", costs[i]);
i = i + 1;
}
}
Why do I get in exception error? The program looks simple enough! It compiles without problems but as soon as I input a number it says that "this program has stopped working". Thanks!!

scanf("%d", costs[i]);
Should be:
scanf("%d", &costs[i]);// &cost[i] gets the address of the memory location you want to fill.

It should be
while(i < 5) {
scanf("%d", &costs[i]);
i = i + 1;
}
a little typo I assume, anyway you need to provide the address of the element of the array you want to scan the integer into.

I would guess it's this line:
scanf("%d", costs[i]);
It should be:
scanf("%d", &costs[i]);
scanf needs a pointer to the variable in which it should put the read result.
This looks like a homework question, judging by the comment about the program have multiple functions. If functions are new, then pointers have probably not been covered yet. In that case, read my explanation as:
scanf needs a & before the variable in which it should put the read result. You'll learn why in a few weeks.

I think you'll need to change you scanf line to
scanf("%d", &costs[i]);
You need to pass the address of the int to have user input written to it. Your current code passes the value of costs[i]. This is undefined so will point to an unpredictable, and probably not writeable, location in memory.

Related

Getting segmentation fault after while loop

Hi i have a project for tommorrow which i want to finish but im stuck. Im pretty new at this so don't be harsh.Basicly i want my program to ask how many numbers did the user play. How much money, after it asks for the lottery numbers and puts then in a border,then it asks for the users numbers,puts in on a second border and then i want to compare the 2 of them and if they have a same number it will add to 'sum'.
#include <stdlib.h>
int main()
{
int k[20],i;
int k2[12],f;
int numbers,sum,n,l,num;
float money,winnings;
l=0;
sum=0;
printf("How many numbers from 1 to 12?\n");
scanf("%d",&num);
printf("How much money?\n");
scanf("%f",&money);
for (i=0;i<19;i++)
{printf("Give lottery numbers\n");
scanf("%d",&k[i]);}
while (l<num){
printf("Give your numbers\n");
scanf("%d", k2 + f); !!fixed!!
l++;}
for (f=0;f<num;f++){
for (i=0;i>19;i++){ !!fixed!!
if ((k[i])==(k2[f])) !!! and here i think its a mistake.
{
sum=sum+1;
}
}
}
printf("You got %d numbers out of %d",sum,num);
if ((sum=1) && (num=1));
{winnings=(money*2,5);
printf("Won %f",winnings);}
if ((sum=1) && (num=2));
{winnings=(money*1);
printf("won %f",winnings);}
if ((sum=2) && (num=2));
{winnings=(money*5);
printf("Won %f",winnings);}
system("pause");}
It doesn't appear that f has ever been initialized to anything. Therefore,
scanf("%d",k2[f]);
Will result in undefined behavior, and is the likely cause of the crash.
Additionally, you need to fix your indentation. Furthermore, your loop is off by one. You initialize l to 1, then execute the following loop, whose apparent purpose is reading num numbers:
while (l<num){
So, if, for example, "1" was entered, in order to read only one number, the body of the loop will never execute, since the comparison "1<1" will be false.
It's likely there are other problems with this code, hard to analyze it due to bad indentation.
This loop
for (i=0;i=19;i++){
will never end since i=19 will evaluate to always true.
I think that the intention was:
for (i=0;i<19;i++){
Instead of l, what you probably intended, you are using f, which, as Sam Varshavchik spotted already, is not initialized.
Additionally, you are not passing a pointer to scanf: scanf("%d", k2[f]);. You need scanf("%d", k2 + l); instead, or scanf("%d", &k2[l]), if you prefer.

Why does the program crash when the function is called in c?

I recently had to create a program where the user enters a certain integer N. After that, my int main() had to call a seperate function, int getNextFibonacciNumber(void), which calculates the Nth term in the fibonacci sequence and then prints it. When I compile the code, Vode::Blocks says that there aren't any errors or warnings. This said, when I try to run the program, it automatically crashes. I have read it and re-read it but I am not able to see where it all went wrong. Would anyone be able to shed some light on this mysery? Thank you very much! When the program crashes, it says: filename.exe has stopped working. A problem caused the program to stop working correctly. Windows will close the program and notify you if a solutions is available. However, when the code is compiled in Code::Blocks, everything is fine.
#include <stdio.h>
#include <stdlib.h>
int getNextFibonacciNumber(void);
int main()
{
int N, fibonacci[N];
printf("Enter a positive integer:");
scanf("%d", &N);
printf("The %d th term in the Fibonacci sequence is: %d", N, getNextFibonacciNumber());
}
int getNextFibonacciNumber()
{
int N, i, fibonacci[N];
fibonacci[0] = 0;
fibonacci[1] = 1;
for(i = 2; i < N+1; i++)
{
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
}
return(fibonacci[N-1]);
}
The problem is, that this
int main()
{
int N, fibonacci[N];
invokes undefined behavior. N is not initialized, but used as a C99 variable length array size specifier. Reading a value from a uninitialized variable invokes UB.
To fix this issue you have to write
int main()
{
int N;
printf("Enter a positive integer:");
scanf("%d", &N);
int fibonacci[N];
However there's another problem, namely that you have the same UB causing construct in getNextFibonacciNumber. You have to fix that to. Also the number entered into N is not "communicated" to getNextFibonacciNumber, so I highly doubt that this program worked at all, even if it didn't crash.
Code::Blocks (or rather the compiler Code::Blocks calls) only checks if you have written "legal" c code. It does not (and can not) check if your program does what you want, if your program will exit at any point (or simply run forever), if your program causes errors and crashs and stuff like this.
When you say
int N, fibonacci[N];
I guess you want to create an integer N and an array of the same size. However right now you create an integer N (that has some "random" value, presumably 0) and an array of the FIXED size N.
If you change N late on in your program this does not affect the size of your array "fibonacci" in any way. So if your N was by chance 0 at the beginning of your program than you have created an array of size 0. Even if you read a value (say 5) from the console input. Trying to read and write to this array causes problems.
Moving the part
int fibonacci[N];
below your "scanf" line will fix this problem. At this point N is initialized (and not some random number).
Also be aware that the variable N in the main function
int main()
has no connection at all to the N variable in your function
int getNextFibonacciNumber()
The second N is a newly created variable (again set to some "random" value). If you want to pass data from one function to another you should do it by passing it as an argument in brackets:
int getNextFibonacciNumber( int N)

10 element array

My teacher gave an assignment to me. The question is below:=
Write a program that prompts the user to enter 10 double numbers. The program should accomplish the follwing:
a. Store the information in a 10-element array.
b. Display the 10 numbers back to the user.
I could do all of the above in main().
Hint: You should use loops, not hardcode the values 0 through 9. It should be easy to convert your program to accept 1000 numbers instead of 10.
For a bonus mark, do at least one of the tasks (a or b) in a separate function. Pass the array to the function; do NOT use global (extern) variables.
I confused above. I wrote a program in the source code. Am I doing wrong? It is below:=
#include<stdio.h>
int main(void)
{
int number[10];
int i;
for (i = 0; i <10; i++)
printf("%d.\n", i, number[i]);
printf("\n\nPress [Enter] to exit program.\n");
fflush(stdin);
getchar();
return 0;
}
Thanks.
Not too bad so far, I'd like to make the following comments:
if you need to input double numbers, you should probably use double rather than int.
you need a statement (maybe in your current loop but possibly in another loop preceding the current one) which inputs the numbers. Look into scanf for this.
Using %d with printf is for integers, not doubles. You will have hopefully already figured out the format string to used when you looked into scanf above.
Bravo for using the correct int main(void) form and for not including conio.h :-)
Once you've figured those bits out, then you can worry about doing it in a separate function.
Based on the code you have given above, I would suggest reading up on the following:
scanf
functions in C, particularly passing arrays to functions: this link should be good.
Note to OP: If you were able to do (a) and (b) in main(), the code above is not complete. It would be nice the functions you created for getting (a) and (b) above done for getting to the root of your "confusion".
Let me know in case you need more help.
HTH,
Sriram
Try this it may sloves your problem.
#include<stdio.h>
int main(void)
{
double number[10];
int i;
printf("Enter double numbers:");
for (i = 0; i <10; i++)
scanf("%lf",&number[i] );
printf("The numbers you entered are:");
for (i = 0; i <10; i++)
printf("%lf\n",number[i] );
return 0;
}

reversing a string of integers user enters (C)

What I want to do is reverse a string of numbers that the user enters. what happens is it compiles and runs till i hit enter after the scanf. then I get some Microsoft runtime error... what's going wrong???
NOTE: this is homework, but i've got the logic figured out. what baffles me is this error.
#include <stdio.h>
int main()
{
unsigned int giveStr = 0;
char* charIt;
printf("Enter a number to be reversed.\t");
scanf("%d", &giveStr);
fflush(stdin);
sprintf(charIt, "%d", giveStr);
revStr(giveStr);
getchar();
return 0;
}
revStr(unsigned int n)
{
char buffer[100];
int uselessvar, counter = 0;
for (; n > 0;)
{
uselessvar = sprintf(&buffer[counter], "%d", n);
counter++;
}
for (counter = 0; counter > 0;)
{
printf("%c", buffer[counter]);
counter--;
}
return 0;
}
EDIT: flushing stdin for newlines :/ and also image here just not with that program. with mine.
You are trying to access memory which is not allocated in:
sprintf(charIt, "%d", giveStr);
Change char* charIt; to char charIt[50]; and all should be well (well, at least the segmentation fault part)
Also... pass charIt to revStr, as charIt contains the string with our number.
Then, a simple for loop in revStr will do the trick (what was the purpose of the second one, anyway?)
void revStr(char *giveStr)
{
int counter;
for (counter = strlen(giveStr)-1; counter >= 0; counter--)
{
printf("%c", giveStr[counter]);
}
printf("\n");
}
This will print each char our char representation has from the last one till the first one. You should read more on for loops.
For your home work problem, if you have the K&R book, turn to section 3.5 and read it thoroughly.
Note the functions reverse() and itoa(). They should give you a pretty good idea on how to solve your problem.
How does your program get out of the for (; n > 0;) loop? Won't counter simply increase until you get a bus error?
ED:
Respectfully, I think the claim that "i've got the logic figured out" is a little optimistic. :^) Doubtless someone will post the way it should have been done
by the time I'm done writing this, but it's probably worth drawing attention to what went wrong (aside from the memory allocation problems noted elsewhere):
Your first loop, "for (; n > 0;)", is strange because you're printing the entire number n into the buffer at counter. So why would you need to do this more than once? If you were selecting individual digits you might, but you're not, and obviously you know how to do this because you already used "sprintf(charIt, "%d", giveStr);". [Aside: giveStr isn't a great name for an unsigned integer variable!]
Your second loop also has strange conditions: you set counter to 0, set the condition that counter > 0, and then decrease counter inside. This obviously isn't going to loop over the characters in the way you want. Assuming you thought the first loop was character-by-character, then maybe you were thinking to loop down from counter-1 to 0?

Simply C loop is driving me nuts

So I have only ever programmed in c++, but I have to do a small homework that requires the use of c. The problem I encountered is where I need a loop to read in numbers separated by spaces from the user (like: 1 5 6 7 3 42 5) and then take those numbers and fill an array.
the code I wrote is this:
int i, input, array[10];
for(i = 0; i < 10; i++){
scanf("%d", &input);
array[i] = input;
}
EDIT: added array definition.
any suggestions or hints would be very highly appreciated.
Irrespective of whatever is wrong here, you should quickly learn to NEVER write code that does not check the return value from any API call that you make. scanf returns a value, and you have to be interested in what it says. If the call fails, your logic is different, yes?
Perhaps in this case it would tell you what's going wrong. The docs are here.
Returns the number of fields
successfully converted and assigned;
the return value does not include
fields that were read but not
assigned. A return value of 0
indicates that no fields were
assigned.
This code working good.
If your numbers is less than 10, then you must know how many numbers is before you start reading this numbers, or last number must be something like 0 to terminate output then you can do while(true) loop, but for dynamically solution you must read all line into string and then using sscanf to reading numbers from this string.
You need the right #include and a proper main. The following works for me
#include <stdio.h>
int main(void) {
/* YOUR CODE begin */
int i, input, array[10];
for (i = 0; i < 10; i++) {
scanf("%d", &input);
array[i] = input;
}
/* end of YOUR CODE */
return 0;
}
i'm not a c programmer but i can suggest an algorithm which is to use scanf("%s",&str) to read all the input into a char[] array then loop over it and test using an if statment if the current char is a space, if it is then add the preceeding number to the array

Resources