C Array program is crashing with segmentation fault - c

I am learning array and just wrote this small program to see how it works. but its crashing with segmentation faul which i understand mean i am writing my variable / function to an memory place not allotted to it. But I cant figure how. Can anyone let me know please?
i am calling introArray from my main().
int introArray (void)
{
int total, ctr;
printf("enter how many students \n");
scanf("%d", &total);
int students[total];
ctr = 0;
while ( students[ctr] <= total)
{
printf("enter student %d DOB in mmddyy \n", ctr );
scanf("%d", students[ctr]);
ctr++;
}
return 0;
}

In your code, there is one implementation logic issue. The total number of students is total and hence, your while loop should be
while(ctr < total)
The data to be read also should scanf("%d", &students[ctr]); There is an ampersand missing

ctr goes beyond total. This way you are going out of bound
Change the loop to
while (ctr < total)
{
printf("enter student %d DOB in mmddyy \n", ctr );
scanf("%d", &(students[ctr]));
ctr++;
}

I think
scanf("%d", students[ctr]);
should be
scanf("%d", &students[ctr]);

This line
while ( students[ctr] <= total)
is not protection against reading past your array bounds inside the loop. This will stop you reading past the end of your array provided you use ctr as your index
while ( ctr < total)
you need the strict inequality as array indices are zero based.
In addition, your scanf call inside your while loop is wrong - the second argument should be a pointer and currently you pass an integer. It should be
scanf("%d", &students[ctr]);

Related

Error: Stack around the variable "m" is corrupted

Im trying to make a program which says how many times a specific digit appears on a 100 numbers sequence.
Meanwhile I got this error and I can´t understand what is the solution to this. I´d appreciate if you could get me some tip or the solution.
#include <stdio.h>
int main() {
int i, m, digit, val[99], count=0;
printf("Enter a number:");
scanf("%d", &val[0]);
while (val[0] < 0) {
printf("Enter a number:");
scanf("%d", &val[0]);
}
for (i=1;i<101;i++) {
val[i]=val[0]++;
printf("%d\n", val[i]);
}
printf("Enter a digit:");
scanf("%d", &m);
while (m<0||m>9) {
printf("Enter a digit:");
scanf("%d", &m);
}
do {
digit=val[i]%10;
val[i]=val[i]/10;
if (digit==m) {
count++;
}
}while (val[i]>0);
printf("The digit %d is printed %d times in this sequence.", m, count);
}
In the for loop you step outside of the array val of which the last index is 98. Instead of hard-coding the length of the array in several places it is more convenient to use a length macro, like this:
#define LEN(anArray) (sizeof (anArray) / sizeof (anArray)[0])
...
for (i = 1; i < LEN(val); i++) {
...
Also, in the do-while loop the index i is outside of the array bounds of val. You also need to check the return value of scanf to make sure the input is valid. The last printf statement also needs a trailing newline.
Edit: Note that LEN only handles "real" arrays; arrays passed to functions are received as pointers.
You allocated only int /* ... */ val[99] (only val[0] to val[98] are available) and accessed upto val[100] because the loop condition is i<101.
This will lead to dangerous out-of-range write (undefined behaior).
Allocate enough elements like int /* ... */ val[101] or fix the loop condition not to cause out-of-range access.
Also you didn't set value of i after the for (i=1;i<101;i++) loop, so value of uninitialized element will be used in the do ... while loop. Values of uninitialized elements of non-static local variables are indeterminate and using the value invokes undefned behavior.
Set i to proper value before the loop or change the indice i to proper thing.

Printing non duplicate in C array

I was working on a program for my intro to C class (xtra credit assignment) and can't figure out how to discard duplicates numbers on an array. The problem asks to only print non duplicates; so I able to print the first number, compare the following and print if different, I discard the next if a duplicate, but the thing is I've only figured out how to compare the one number it following one, I figured I could do another for loop inside the for loop, but I'm getting super confused and just can't figure it out. I've already submitted my code last week, I've just been working on this trying to figure it out for myself so any help/guidance would be greatly appreciated.
"EDIT: Here's the problem: Use a single-subscripted array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, print it only if it's not a duplicate of a number already read. Provide for the worst case in which all 20 numbers are different. Use the smallest possible array to solve this problem"
Thanks in advance, and any advice on how I'm writing my program would also be appreciated as I'm a total noob, and trying to be a good programmer with as little bad habits as possible.
#include <stdio.h>
#include <stdlib.h>
#define AS 20
void findDuplicate (int af[], int fAS);
int main(){
int a[AS], i , j, k;
int last = 0;
printf("Enter %d numbers between 10 and 100:\n", AS);
for (i = 0; i < AS; i++){
scanf("%d",&a[i] );
if (a[i] >= 10 && a[i] <= 100 ){
continue;
} else {
printf("You must enter values between 10 - 100\n");
i = i -1;
}
}
findDuplicate(a, AS);
system ("pause");
return 0;
}
void findDuplicate (int af[], int fAS){
int c;
printf("You entered ");
for (c=0; c < fAS; c++){
if (af[c] != af[c+1]){
printf("%d ", af[c]);
}
continue;
}
printf("\n");
}
You should first define an Array which can save as many variables as you want ..
Lets say you are comparing for 10-100 which means 91 possible different digits.
so , define array with the size of 91. and then do the scanning in for loop for 91 times to find out if you have that variable entered previously. If not then save it and display it ,else discard it.

How can i add numbers to an array using scan f

I want to add numbers to an array using scanf
What did i do wrong? it says expected an expression on the first bracket { in front of i inside the scanf...
void addScores(int a[],int *counter){
int i=0;
printf("please enter your score..");
scanf_s("%i", a[*c] = {i});
}//end add scores
I suggest:
void addScores(int *a, int count){
int i;
for(i = 0; i < count; i++) {
printf("please enter your score..");
scanf("%d", a+i);
}
}
Usage:
int main() {
int scores[6];
addScores(scores, 6);
}
a+i is not friendly to newcomer.
I suggest
scanf("%d", &a[i]);
Your code suggests that you expect that your array will be dynamically resized; but that's not what happens in C. You have to create an array of the right size upfront. Assuming that you allocated enough memory in your array for all the scores you might want to collect, the following would work:
#include <stdio.h>
int addScores(int *a, int *count) {
return scanf("%d", &a[(*count)++]);
}
int main(void) {
int scores[100];
int sCount = 0;
int sumScore = 0;
printf("enter scores followed by <return>. To finish, type Q\n");
while(addScores(scores, &sCount)>0 && sCount < 100);
printf("total number of scores entered: %d\n", --sCount);
while(sCount >= 0) sumScore += scores[sCount--];
printf("The total score is %d\n", sumScore);
}
A few things to note:
The function addScores doesn't keep track of the total count: that variable is kept in the main program
A simple mechanism for end-of-input: if a letter is entered, scanf will not find a number and return a value of 0
Simple prompts to tell the user what to do are always an essential part of any program - even a simple five-liner.
There are more compact ways of writing certain expressions in the above - but in my experience, clarity ALWAYS trumps cleverness - and the compiler will typically optimize out any apparent redundancy. Thus - don't be afraid of extra parentheses to make sure you will get what you intended.
If you do need to dynamically increase the size of your array, look at realloc. It can be used in conjunction with malloc to create arrays of variable size. But it won't work if your initial array is declared as in the above code snippet.
Testing for a return value (of addScores, and thus effectively of scanf) >0 rather than !=0 catches the case where someone types ctrl-D ("EOF") to terminate input. Thanks #chux for the suggestion!

User input for array index+index value in C

This is a question that I have found on this site but the responses were not directly related to what I believe my problem is. I am a little embarrassed because I'm still very much an amateur. I am asking the user for how many GPAs they would like to enter. Then I am asking for input for each index. The problem is each index is returning 0. So I'm pretty sure I am messing up either the variable type or possibly the way I am incrementing the index. This is a homework problem and I am looking more for guidance than a complete give away.
#include<stdio.h>
main()
{
char Rspns;
int i, toCount, Total;
float GPA[toCount];
printf("\n\tYou can average up to 30 GPAs.");
printf("\n\tPlease choose how many GPAs you would like to average:");
scanf(" %d" , &toCount);
//assign how many indexes array should have
for(i = 0; i<toCount; i++)
GPA[i] = i++;
do
{
system("cls");
printf("\n\nEnter a GPA:");
scanf(" %f" , &GPA);
printf(" %f" , GPA[i]);
Total += GPA[i];
getch();
system("cls");
printf("\n\n\tWould you like to average the current amount of GPA's?");
printf("\n\nY/N: ");
scanf(" %c" , &Rspns);
if(Rspns == 'y' || Rspns == 'Y')
{
Total = Total / toCount;
printf("The average of those GPAs is %.1f" , Total);
getch();
}// end response
}while(i<=toCount);//end forCount
Total = Total / toCount;
}
int i, toCount, Total;
float GPA[toCount];
toCount is not initialized at this point.
Total += GPA[i];
same here, Total starts with an indeterminate value.
This
scanf(" %f" , &GPA);
is absolutely not what you want to do: remember, arrays and pointers are closely related in C - see this SO answer.
scanf(" %f" , &(GPA[i]) );
will scan the value into the i'th element of the array
I think you should be scanning into the specific float as opposed to scanning into the whole array
scanf("%f", &GPA[i]);
also, check your types for printf, the compiler is spewing out warnings.
Either initialise your GPA array to be a fixed size and validate toCount to be between 1 and the maximum, or use the memory allocation functions malloc or calloc to dynamically allocate your GPA array once you know the size (and free when finished with it).
I can't work out what you are trying to do where you say "assign how many indexes array should have", but there's no need to enter values into the array that you are going to subsequently overwrite (you can use calloc as described above to initialise them all to zero). Note that you should scan into the ith element of the GPA array (&GPA[i]), not into &GPA which is always the first element.
Also, be careful about the i++ because you are incremementing i twice each loop. Although that part of your code is unnecessary, it's a trap to watch out for in general.

Input in a 2-D array

I was trying to solve a question on 2-D matrix, but unfortunately the matrix input was giving an error. This is the code:
int arr[4][4];
int r, c;
scanf("%d", &r);
scanf("%d", &c);
int i, j;
fflush(stdin);
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
scanf("%d", &arr[i][j]);
When I run this, it takes extra input.
For example: if r = 2 and c = 2> then it takes 6 input and then hangs. What to do?
If r=2 and c=2, it executes the first 2 scanf and then the 2x2 scanf of your 2D loop.
This makes 2 + 2x2 = 6.
After the last scanf, if your program is finished, it simply closes, that's normal.
I have copied your code and tried executing it and I observed that it is showing the behaviour told by you if we are taking r and c greater than their limits. So use proper limits.
I think the problem with your code is that you've allocated a fixed amount of space for your array but allowed the user to provide an arbitrary number of inputs by making the bounds of your loop the user-provided r and cvariables. Thus if the user provides r=6 and c=6, at some point your loop will attempt to dereference arr[5][5], which is invalid since you've defined int arr[4][4];. If you want to allow the user to create as many rows and columns as they want, you should initialize arr with the user-provided input, like this:
int r,c;
scanf("%d",&r);
scanf("%d",&c);
int arr[r][c];
In your code you have simply run a loop and how much value will be scan depend on the how many loops has executed.
Suppose you take r=1,c=1.
In this condition for every "r" value c will executed single time.
So When your value will be larger than the array size that time it will give you abnormal behavior.
if you will firstly input the value of "c", and "r"after that it will behave normally.
int r, c;
scanf("%d", &r);
scanf("%d", &c);
int arr[r][c];

Resources