CodeChef runtime error(sigsegv) - c

CodeChef Problem:
Shivam is the youngest programmer in the world, he is just 12 years old. Shivam is learning programming and today he is writing his first program.
Program is very simple, Given two integers A and B, write a program to add these two numbers.
Input
The first line contains an integer T, total number of test cases. Then follow T lines, each line contains two Integers A and B.
Output
Add A and B and display it.
Constraints
1 ≤ T ≤ 1000
1 ≤ A,B ≤ 10000
Example
Input
3
1 2
100 200
10 40
Output
3
300
50
#include <stdio.h>
int main()
{
int T, A, B, i, sum[T];
scanf("%d", &T);
for(i=0;i<T;i++)
{
scanf("%d",&A);
scanf("%d",&B);
sum[i]=A+B;
}
for(i=0;i<T;i++)
{
printf("\n%d", sum[i]);
}
}
Error
Runtime Error SIGSEGV - I searched it, it says array out of bounds.

T has an indeterminate value when you declare sum[T]. Instead, do:
int main()
{
int T, A, B, i;
scanf("%d", &T);
int sum[T];
for(i=0;i<T;i++) ...
Ans you should check the return value of scanf.

If you want to allocate the memory runtime (during the programs execution) it would be more appropriate to use a function such as "malloc". Here is a short example.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int T, A, B, i;
int *sum;
scanf("%d", &T);
if (T <= 0) /*Check if the value of T is appropriate*/
{
fprintf(stderr, "Invalid argument T!\n");
}
/* Dynamically allocate the memory */
sum = (int *)malloc(sizeof(int)*T);
if (sum == NULL)
{
fprintf(stderr, "Failed to allocate memory!\n");
}
for(i=0;i<T;i++)
{
scanf("%d",&A);
scanf("%d",&B);
sum[i]=A+B;
}
for(i=0;i<T;i++)
{
printf("\n%d", sum[i]);
}
/* Free the allocated memory once you are not needing it anymore in
order to avoid memory leaks */
free(sum);
return (0);
}
Note: This is just an example how to avoid the runtime error I have not taken a close look at the rest of the logic related with the for loops.

Declare sum[T] after taking the input value of T

Related

How to calculate 3 prime numbers in sequence and divide two of them

That is the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int min=0, med=0, max=0, n=0, t=2,
k=2, j=2, flag=0, counter=0,
a=0, b=0, c=0;
scanf("%d%d", &min, &max);
for(; min<=max; min++){
while(t <= min/2){
if(min%t==0){
flag=1;
break;
}
t++;
}
if(flag==0){
counter++;
}
t=2;
flag=0;
}
printf("%d", counter);
return 0;
}
This code prints all the prime numbers of a given range.
I want to store the first 3 prime numbers into different variables, and then check if the minimum and the maximum divided by two equals the mid one.
Also, I want to keep doing it until the program reaches the end of the range.
I have no idea how to store the first three in different variables inside the loop, or even if have I cannot do it.
I'd appreciate any hints.
I am still wondering how could I implement that inside the loop, because it only gives me one value which is "min".
You could store the current found prime in another variable (c) after you stored that variable in another variable (b) after you stored that variable in another variable (a); this way, you have the last seen three primes at hand.
a = b, b = c, c = min;
if (b-a == c-b) printf("%d %d %d\n", a, b, c);

functions in c programming

I am new to c ,while i am writing a basic program in c ,it is showing two answers ..1)when i declare and intialize variables separately 2)when I declare and initialize variable in a same line.can any one tell me my mistake please?
#include <stdio.h>
#include <stdlib.h>
void sum()
{
printf("enter the numbers to be added\n");
int x=scanf("%d",&x);
int y=scanf("%d",&y);
int sum=(x+y);
printf("the sum of two numbers is %d\n",sum);
}
int main()
{
printf("welcome to addition calculator\n");
sum();
return 0;
}
I am getting 2 as answer when i gave 3 and 4 as inputs
scanf("%d", &x) will store the read number into x. It will return the number of successfully read fields (1 in your case). If you assign that return value to x afterwards, you overwrite whatever the user entered with that 1. And 1 + 1 produce 2.
Solution:
int x;
int y;
scanf("%d",&x);
scanf("%d",&y);
As David reminds in comments, you might want to check that all fields were read successfully. For example, in your case, if you enter a non-digit, scanf will not resolve the %d field as successful, and will return 0. You can test this result to make sure the user did what they were supposed to do:
int x;
int y;
while (scanf("%d", &x) != 1) {
printf("Enter a NUMBER, you illiterate buffoon!\n");
}
while (scanf("%d", &y) != 1) {
printf("Enter a NUMBER! You managed with %d, how is this suddenly hard now?!\n", x);
}
scanf() function returns 1 if it scan successfully otherwise it return 0. That's why when you put an integer to x, scanf() return 1 and assign it to x(x=1). Same for y(y=1).
As x=1 and y=1.
sum = 2

how to use scanf to scan double and char at the same time into a double array in C

I have a project to do which asks me to record the address of two vectors into a double array according to user's input. However. For example, if user writes
3
1 2 3
3 4 5
it means that the vectors are 3 dimensional and the two vectors are (1,2,3)(3,4,5). If user writes,
2
1 2
2 3
it means that the vectors are 2 dimensional and the two vectors are (1,2)(2,3). I need to record the coordinates of these two vectors into two double arrays x, and y. How can I read the coordinates into these two arrays using scanf? (I don't know if the user writes in the correct format, it's possible for them to write letter or other symbol at the place where they are supposed to just write number. If they write chars other than number, i need to return -1.)
my code so far is
double x[100];
char c;
c = getchar();
do {
scanf("%lf",x)}
while (c!= '\n');
As far as I understand your problem, here is a code that should solve it.
#include <stdio.h>
#include <stdlib.h>
#define NB_VECTORS 2 //Increase if you have more than 2 vectors
int* readVector(int size) {
// Allocation fits the size
int* vector = malloc(size*sizeof(int));
//While the vector are the same size it works
for (int i = 0; i < size; i++)
if (scanf("%d", vector+i) != 1)
return null; //bad input
return vector;
}
int main(int argc, char** argv) {
int size;
scanf("%d", &size);
//Each line is vectorized inside vectors[i]
int* vectors[NB_VECTORS];#
for (int i = 0; i < NB_VECTORS; i++)
vectors[i] = readVector(size);
return 0;
}
[EDIT]
returns the number of items it has filled -> cf http://www.cplusplus.com/reference/cstdio/scanf/
Maybe you simply need something like this (simplistic, minimal, no error checking example):
int main()
{
int x[3], y[3];
int dimension;
scanf("%d", &dimension);
if (dimension == 3)
{
scanf("%d %d %d", &x[0], &x[1], &x[2]);
scanf("%d %d %d", &y[0], &y[1], &y[2]);
}
else if (dimension == 2)
{
scanf("%d %d", &x[0], &x[1]);
scanf("%d %d", &y[0], &y[1]);
}
...
return 0;
}
scanf is not a good function for parsing user input. It accepts 2.1sdsa2 as a float with the value 2.1 and it accepts 2.1sdsa2 as an int with value 2. The scanf should only be used when you know that the input is valid.
If you are required to use scanf, you can scan into a string and then write your own parse to check that the input is valid.
A simple example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10];
while (1 == scanf("%s", s))
{
printf("%s\n", s);
if (strcmp(s, "s") == 0) break;
}
return(0);
}
The program continues until the input is s
Example of output:
1 2.0 2.6
1
2.0
2.6
2a 4567 2.a23
2a
4567
2.a23
s
s
Notice that scanf returns when it sees a space. So the input 1 2 3 will be 3 loops (aka 3 substrings returned).
So instead of just printing, you could put your parser inside the while:
while (1 == scanf("%s", s))
{
// Parse the string s and add value to array
}

Can't find the error in minimum difference between two numbers on array in C

So I'm really new to programming. I need to write a program that, if I give it any array of integers, it'll be able to find the two numbers closest to each other, and then give the difference between those two numbers. Also, the first number must be the number of integers that are going to be in the array.
So for example, I give it 3 1 4 8. The first 3 means that there will be three integers, so it must find the closest two numbers between those three. In this case, it's 4 - 1 = 3, so the output should be 3, but when I write it it gives me 16.
This is what I have, and I don't know what's wrong:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i;
printf("Write numbers here\n");
scanf("%d", &n);
int st[n];
for(i=0;i<n;i++)
scanf("%d",&st[i]);
int a, b, str[n*n], minimum, c;
/* here I'll make a new array, and its elements will be all the
differences between all the elements of the previous one */
for(a=0;a<n;a++)
for(b=0+a*n;b<n;b++) {
if(st[b-a*n]==st[a])
str[b]=32000;
else
str[b]=abs(st[b-a*n]-st[a]);
}
// here I'll find the smallest element on the last made array
minimum = str[0];
for(c=0;c<n*n;c++)
{
if(str[c]<minimum);
{
minimum=str[c];
}
}
printf("%d", minimum);
return 0;
}
Edit: I tried to fix it with your answers but it still doesn't work.
New code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i;
printf("Write numbers here\n");
scanf("%d", &n);
int st[n];
for(i=0;i<n;i++)
scanf("%d",&st[i]);
int a, b, minimum;
minimum = st[0];
for(a=0;a<n;a++)
for(b=0;b<n;b++) {
if((st[b] != st[a]) && (abs(st[b]-st[a]))<minimum)
minimum = abs(st[b]-st[a]);
}
printf("%d", minimum);
return 0;
}
Edit 2: Ok, I fixed it now. Thanks a lot ^^
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main() {
int n, i;
printf("write numbers here\n");
scanf("%d", &n);
int st[n];
for(i=0;i<n;i++)
scanf("%d",&st[i]);
int a, b, minimum;
minimum = INT_MAX;
for(a=0;a<n;a++)
for(b=a+1;b<n;b++) {
if((abs(st[b]-st[a]))<minimum)
minimum = abs(st[b]-st[a]);
}
printf("%d", minimum);
return 0;
}

C program crashes on printing array

I am learning C at the moment, and am trying to build a simple interpreter. It takes one character and one number. The program below only uses 'r' for the char. The 'r' stands for the range (of the natural numbers) and the digit after it specifies the length of the range.
Example Execution:
Enter:
r 9
0 1 2 3 4 5 6 7 8
What happens instead:
Enter:
r 9
And here the program crashes. So I believe the error lies in the printing of the array.
The code in question is here:
#include <stdio.h>
#include <stdlib.h>
int* range(int i) {
int *a=(int*) malloc(i * sizeof(int));
int j;
for(j=0;j<i;j++)
a[j]=j;
return a;
}
void printArray(int a[], int length) {
int i;
printf("\n");
for(i=0;i<length;i++)
printf("%d ", a[i]);
}
int main() {
char c;
int n = 1;
while(n>=0){
printf("\nEnter:\n\t");
scanf("%c %d", c, n);
if(c='r')
printArray(range(n), n);
}
return 0;
}
So what is causing the program to crash?
Your arguments to scanf are wrong, you need
scanf("%c %d",&c, &n);
Your fundamental problem here is that you have no evidence about where the crash is happening, as it happens I bet it's in scanf().
I recommend you adopt two debugging techniques:
a). Add print statements in your code so you know what's happening
b). Use an interactive debugger so you can step through and see what's going on.

Resources