I am trying to solve problem 1A on codeforces
but i keep getting Test: #1, time: 0 ms., memory: 1828 KB, exit code: 1, checker exit code: 0, verdict: RUNTIME_ERROR
you can check my entry here and find my code below , i tried to to run the program locally and it works fine and it passed the test case on the website
#include<stdio.h>
int calculateSquare(int n , int m , int a){
int length=0;
int width = 0;
if(n%a != 0){
length = (n/a)+1 ;
}
else{
length = n/a ;
}
if(m%a != 0){
width = (m/a)+1 ;
}
else{
width = m/a ;
}
return length*width ;
}
void main(){
int n,m,a ;
scanf("%d %d %d",&n,&m,&a);
int output = calculateSquare(n,m,a);
printf("%d",output);
}
int calculateSquare(int n , int m , int a)
return type is int and return value is length*width
In the worst case a would be 1 and n, m would be 109 as stated in the problem
Input
The input contains three positive integer numbers in the first
line: n, m and a (1 ≤ n, m, a ≤ 109).
So the return type int cannot hold the returned value for such case.
Better using long long int if the compilation is conform with C99 standard.
I modified your code as given below which seems to be working fine :
#include <stdio.h>
long long int calculateSquare(long n , long m , long a){
long length=0;
long width = 0;
if(n%a != 0){
length = (n/a)+1 ;
}
else{
length = n/a ;
}
if(m%a != 0){
width = (m/a)+1 ;
}
else{
width = m/a ;
}
long long store = length*widthl
return store;
}
int main(){
long int n,m,a ;
scanf("%ld %ld %ld", &n, &m, &a);
long int output = calculateSquare(n,m,a);
printf("%ld\n", output);
return 0;
}
when trying to 'beat the clock', it is best to not use 'expensive' I.O functions.
Suggest the following two functions:
#include <stdio.h>
void fastRead( size_t *a );
void fastWrite( size_t a );
inline void fastRead(size_t *a)
{
int c=0;
// note: 32 is space character
while (c<33) c=getchar_unlocked();
// initialize result value
*a=0;
// punctuation parens, etc are show stoppers
while (c>47 && c<58)
{
*a = (*a)*10 + (size_t)(c-48);
c=getchar_unlocked();
}
//printf( "%s, value: %lu\n", __func__, *a );
} // end function: fastRead
inline void fastWrite(size_t a)
{
char snum[20];
//printf( "%s, %lu\n", __func__, a );
int i=0;
do
{
// 48 is numeric character 0
snum[i++] = (char)((a%10)+(size_t)48);
a=a/10;
}while(a>0);
i=i-1; // correction for overincrement from prior 'while' loop
while(i>=0)
{
putchar_unlocked(snum[i--]);
}
putchar_unlocked('\n');
} // end function: fastWrite
This occurs when an uninitialized variable is passed as an Array or Vector size.
Code with error:
int m;
vector<int> arr(m);
//throws Exit code 2147483647
//default value of uninitialized int variable is 4201296 > 10^5
//so the vector<int> can't be created.
Correct answer:
int m;
cin>>m; //this works
vector<int> arr(m);
Related
#include <stdio.h>
void DectoBin(int *n);
int *p;
int position;
int main()
{
int num;
printf("Input number : ");
scanf("%d", &num);
DectoBin(&num);
for (int i = position - 1; i >= 0; i--)
{
printf("%d", p[i]);
}
}
when launch this code, this code compile well...
but I have a error message 'zsh : segmentation fault'
void DectoBin(int *n)
{
int binary[20] = { 0, };
p = binary;
while (1)
{
binary[position++] = *n % 2;
*n = *n / 2;
if (n == 0)
break;
}
return;
}
so, What parts should be corrected to solve the problem??
I think the minimum change to make it seem to work is this:
// you use *n as an integer, but test "n"
// (which is its address, and will never be zero).
// So the while loop goes on indefinitely, eventually overflowing the buffer.
if (*n == 0)
break;
A more serious problem is that the buffer is allocated backwards: you have the pointer outside the function and the buffer is allocated on the stack inside the function. So, as soon as the function exits, the buffer is no longer "legal". The data is probably still there (on my system, it is) and you might even be able to use it as if nothing was amiss. On a short program, and depending on your system, you might not notice that the code has become a time bomb.
You ought to estimate how much of a buffer you need (how many binary digits), then allocate memory on the heap, using malloc(), check it worked, and pass that memory to the function - which will allocate nothing - together with the allocated size, so it can ensure it doesn't overflow the buffer.
The function would then return how many digits to actually print.
#include <stdio.h>
#include <malloc.h>
size_t DectoBin(size_t maxdigits, int *digits, int number);
int main() {
int num;
int *buffer;
size_t maxdigits, position;
printf("Input number : ");
scanf("%d", &num);
// Always check your inputs.
if (num < 0) {
printf("Negative numbers are not supported yet\n");
return 1;
}
maxdigits = 1;
{
// Calculate how many digits are required. Could use ceiling of base-2 logarithm of num.
int tmp = num;
while (tmp > 0) {
maxdigits ++;
tmp /= 2;
}
}
buffer = malloc(maxdigits * sizeof(int));
if (NULL == buffer) {
fprintf(stderr, "Out of memory\n");
return 2;
}
position = DectoBin(maxdigits, buffer, num);
for (size_t i = position; i > 0; i--) {
printf("%d", buffer[i-1]);
}
printf("\n");
return 0;
}
size_t DectoBin(size_t maxdigits, int *digits, int number) {
size_t pos = 0;
do {
digits[pos++] = number % 2;
number /= 2;
} while (number && pos < maxdigits);
return pos;
}
For starters there is a typo
if (n == 0)
It seems you mean
if (*n == 0)
Though there is no any sense to accept a number indirectly through a pointer to it.
You are using the local array binary with automatic storage duration within the function DectoBin
void DectoBin(int *n)
{
int binary[20] = {
0,
};
//...
that will not be alive after exiting the function. So the pointer p will have an invalid value.
Also it is unclear why you are using the magic number 20 in the array declaration. At least you should use the value of the expression sizeof( int ) * CHAR_BIT.
Also it is a bad idea to use global variables.
At Least you could declare the array within the function with the storage-class specifier static and return a pointer to the array from the function.
Pay attention to that for negative numbers you can get an incorrect result.
For example the function can be implemented the following way as shown in the demonstration program below.
#include <stdio.h>
#include <limits.h>
#include <string.h>
const char * DecToBin( int n )
{
static char binary[CHAR_BIT * sizeof( int ) + 1 ];
memset( binary, 0, sizeof( binary ) );
unsigned int un = n;
char *p = binary + sizeof( binary ) - 1;
do
{
*--p = '0' + ( un & 1 );
} while ( un >>= 1 );
return p;
}
int main( void )
{
printf( "%d -> %s\n", 123, DecToBin( 123 ) );
printf( "%d -> %s\n", -123, DecToBin( -123 ) );
}
The program output is
123 -> 1111011
-123 -> 11111111111111111111111110000101
so i am getting some kind of error , that after my array input the code doesnt run .
i wanted to see if my method is wrong for inputting an array address in as a function parameter and then using it to solve
//find max element , of an array and return its address. using a function
so this is the code :
#include<stdio.h>
int *ReturnMax(unsigned int *NoArray[], unsigned int NoOfTerm)
{
int i;
for(i=0;i<NoOfTerm;i++)
{
if(*NoArray[i]>*NoArray[i+1])
{
return NoArray[i];
}
else
{
return NoArray[i+1];
}
}
}
int main()
{
int NumOfTerm,i;
int *ReturnAddress;
printf("Enter number of Terms:\n");
scanf("%d",&NumOfTerm);
int NumArray[NumOfTerm];
printf("Enter the Array : \n");
for(i=0;i<NumOfTerm;i++)
{
scanf("%d",&NumArray[i]);
}
*ReturnAddress=ReturnMax(&NumArray[NumOfTerm],NumOfTerm);
printf("The Max number is %d and its Address is %d",*ReturnAddress,ReturnAddress);
return 0;
}
For starters the function
int *ReturnMax(unsigned int *NoArray[], unsigned int NoOfTerm)
{
int i;
for(i=0;i<NoOfTerm;i++)
{
if(*NoArray[i]>*NoArray[i+1])
{
return NoArray[i];
}
else
{
return NoArray[i+1];
}
}
}
does not make sense.
At least the return type should be unsigned int *.
The first parameter of the function has the type unsigned int *NoArray[] . It is adjusted by the compiler to the type unsigned int **NoArray.
And you need to declare the array like
unsigned int NumArray[NumOfTerm];
You are calling the function like
*ReturnAddress=ReturnMax(&NumArray[NumOfTerm],NumOfTerm);
that is you are passing a pointer to the memory beyond the array that has the type unsigned int * because the valid range of indices is [0, NumOfTerm).
Moreover the pointer ReturnAddress is not initialized.
And in this call of printf
printf("The Max number is %d and its Address is
there are used invalid format specifiers.
The function can be defined the following way
unsigned int * ReturnMax( const unsigned int NoArray[], size_t NoOfTerm )
{
const unsigned int *max = NoArray;
for ( size_t i = 1; i < NoOfTerm; i++ )
{
if ( *max < NoArray[i] ) max = NoArray + i;
}
return ( unsigned int * )max;
}
And called like
ReturnAddress = ReturnMax( NumArray, NumOfTerm );
printf("The Max number is %u and its Address is %p", *ReturnAddress, ( void * )ReturnAddress);
Here is a demonstrative program
#include <stdio.h>
unsigned int * ReturnMax( const unsigned int NoArray[], size_t NoOfTerm )
{
const unsigned int *max = NoArray;
for ( size_t i = 1; i < NoOfTerm; i++ )
{
if ( *max < NoArray[i] ) max = NoArray + i;
}
return ( unsigned int * )max;
}
int main(void)
{
size_t NumOfTerm;
unsigned int *ReturnAddress;
printf( "Enter number of Terms: " );
scanf( "%zu", &NumOfTerm );
unsigned int NumArray[NumOfTerm];
printf( "Enter the Array:\n" );
for ( size_t i = 0; i < NumOfTerm; i++ )
{
scanf( "%u", &NumArray[i] );
}
ReturnAddress = ReturnMax( NumArray, NumOfTerm );
printf( "The Max number is %u and its Address is %p",
*ReturnAddress, ( void * )ReturnAddress );
return 0;
}
If to input
10
0 1 2 3 4 5 6 7 8 9
Then the program output might look like
Enter number of Terms: 10
Enter the Array:
0 1 2 3 4 5 6 7 8 9
The Max number is 9 and its Address is 0x7ffdb3333194
You are calling ReturnMax with:
*ReturnAddress = ReturnMax(&NumArray[NumOfTerm],NumOfTerm);
This passes to the function the address to NumArray[NumOfTerm] which is outside the bounds of your array, this is probably why your program throws an error. Also you can just pass *ReturnAddress = ReturnMax(NumArray,NumOfTerm); if you change your function to:
int *ReturnMax(unsigned int *NoArray, unsigned int NoOfTerm)
Another thing is that you don't need to dereference in if(*NoArray[i]>*NoArray[i+1]) if you want to compare the values contained. It should be
if(NoArray[i]>NoArray[i+1])
instead
Also if you want to print a pointer you should use %p and not %d inside your
printf("The Max number is %d and its Address is %d",*ReturnAddress,ReturnAddress);
#include <stdio.h>
main()
{
int num[9], i = 0, count = 0;
while (i<10)
{
scanf("%d", &num[i]);
if (num[i] % 2 == 0)
{
count++;
}
i++;
}
printf("we have %d double numbers\n", count);
}
Run-Time Check Failure #2 - Stack around the variable was corrupted
What should I do?
Your while loop hits all values of i from 0 to 9 inclusive, but attempting to access num[9] takes you out of bounds. You'll need to reduce the while loop range:
while (i<9) {
...
}
In addition, you really should give your main() function a return type, since modern compilers don't tolerate it being missing:
int main()
{
...
return 0;
}
The valid range of indices that can be used to access an array with N elements is [0, N - 1] or that is the same [0, N ).
Thus the condition in the while statement
while (i<10)
has to be rewritten like
while (i < 9)
The reason of the error is using "magic numbers" throughout the program.
Try to use named constants instead of magic numbers, In this case it will be easy to understand what magic number is used in what part of the code.
The program can look like
#include <stdio.h>
#define N 9
int main( void )
{
int num[N];
unsigned int count = 0;
unsigned int i = 0;
while ( i < N )
{
scanf( "%d", &num[i] );
if ( num[i] % 2 == 0 ) ++count;
i++;
}
printf( "we have %u double numbers\n", count);
}
Instead of the while loop it would be better to use a for-loop because the variable i is not used outside the loop.
For example
#include <stdio.h>
#define N 9
int main( void )
{
int num[N];
unsigned int count = 0;
for ( unsigned int i = 0; i < N; i++ )
{
scanf( "%d", &num[i] );
if ( num[i] % 2 == 0 ) ++count;
}
printf( "we have %u double numbers\n", count);
}
A more correct approach of declaring indices of arrays is using the type size_t for them.
In fact the array is not used in the program. You could count even entered values without using an array.
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )
I'm finishing a program that I found in my C book but I ran into some issues.
I'm just about done but I keep getting this error
Error 1 error C2440: 'function' : cannot convert from 'double [15]' to '
Why am i getting this compiler error?
void arrayRead(double, int*);
void arrayList(double, int*);
void arraySum(double, int*, int*);
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<ctype.h>
int main()
{
int num, sum = 0;
double array[15];
printf("How many doubles (numbers) would you like in the array (20 max)?\n");
scanf("%d", &num);
printf("Thank you! Now give me %d different doubles (numbers) please!\n", num);
arrayRead(array, &num);
printf("Here are all of your integers again!\n");
arrayList(array, &num);
arraySum(array, &num, &sum);
printf("The sum of these numbers = %d\n", sum);
return 0;
}
void arrayRead(double array[], int* num)
{
for (int i = 0; i < *num; i++)
{
scanf("%lf", &array);
}
}
void arrayList(double array[], int*num)
{
for (int i = 0; i < *num; i++)
{
printf("%.2f\n", array);
}
}
void arraySum(double array[], int*num, int* sum)
{
for (int i = 0; i < *num; i++)
{
*sum = array + *sum;
}
}
best to place prototypes after any #include statements,
just in case the prototype uses something defined in the header file
The size of the array must be a positive number,
so use '%u' to input a positive numbe
and define the max variable as unsigned
The parameters to functions and the parameters passed when calling those functions need to have matching types (or the function type be a 'promotion' of the passed type.
since the array is doubles, all the references should also be double, like the sum variable.
appropriate horizontal white space makes the code much easier to read
do not #include header files those contents are not being used.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//#include <ctype.h>
// prototypes
void arrayRead( double*, unsigned );
void arrayList( double*, unsigned );
void arraySum ( double*, unsigned, double* );
int main( void )
{
unsigned num;
double sum = 0.0;
printf( "How many doubles (numbers) would you like in the array (20 max)?\n" );
if( 1 != scanf( "%u", &num ) )
{
perror( "scanf for size of array failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
// need to add check that user entered value is in range 1...20
double array[ num ];
printf( "Thank you! Now give me %u different doubles (numbers) please!\n", num );
arrayRead( array, num );
printf( "Here are all of your integers again!\n" );
arrayList( array, num );
arraySum( array, num, &sum );
printf("The sum of these numbers = %lf\n", sum);
return 0;
} // end function: main
void arrayRead( double array[], unsigned num )
{
for ( unsigned i = 0; i < num; i++ )
{
scanf("%lf", &array[i]);
}
} // end function: arrayRead
void arrayList( double array[], unsigned num )
{
for ( unsigned i = 0; i < num; i++ )
{
printf("%.2f\n", array[i]);
}
} // end function: arrayList
void arraySum( double array[], unsigned num, double* sum )
{
for ( unsigned i = 0; i < num; i++ )
{
*sum = array[i] + *sum;
}
} // end function: arraySum
Here is the output from a simple run of the answer code:
How many doubles (numbers) would you like in the array (20 max)?
5
Thank you! Now give me 5 different doubles (numbers) please!
1 1 1 1 1
Here are all of your integers again!
1.00
1.00
1.00
1.00
1.00
The sum of these numbers = 5.000000
The functions you have declared have different signatures than the functions you have defined.
Be careful in the declaration you use double instead of double *. It is not the same.
When you call the arrayRead function and company, the compiler sees only the declared functions as the defined functions are after the calls. So the parameters doesn't match.
By the way, in the defined functions you forgot to write the index. You are using the pointer and this can't work. You need to write array[i] inside each loop.
My function is not quite done yet, but what I'm going to do is:
To read in a string of numbers separated by spaces.
Extract the numbers from that string.
Convert them to long ints.
Return the number of numbers read in.
int input( int a, int b, long int *result_array )
{
int ele = 0;
char buffer[200];
char *start, *end;
scanf("%[^\n]%*c", buffer );
start = buffer;
while( ( end = ( strchr( start, ' ' ) ) != NULL ) )
{
result_array = strtol( start, &end, 10 );
ele += 1;
start = end + 1;
}
return ele;
}
It doesn't seem to work properly, I think I'm using strchr wrong.
strtol() returns:
On success, the function returns the converted integral number as a long int value.
If no valid conversion could be performed, a zero value is returned (0L).
you should re write your code as:
end = buffer;
base = 10;
long int = li;
ele = 0;
while(li=strtol (end,&end, base)){
ele += 1;
}
return ele;
You don't need to explicitly use strstr() to locate for next integer. strtol() smart enough and after each conversion it locate end point to next int.
I have written an running code may be your find helpful:
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main (){
char buffer[] = "2001 11 223 444 566";
char * end;
long int li;
end =buffer;
int base =10;
int ele = 0;
while(li=strtol (end, &end, base)){
printf("%ld \n", li);
ele += 1;
}
printf("\nNo of elements: %d", ele);
return 0;
}
its output:
2001
11
223
444
566
No of elements: 5
Link to codepad