Why array self assign value (C program)? [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I declared a two dimensional array as row and col and I left the value empty, but when I check the value in each array position, some of the indexes contain some weird number.

You are looking at uninitilized memory. It can have whatever which value to it. You should never trust the value of a variable you haven't initialized.

Access of an uninitialized value is undefined behavior. You can solve your problem quite simply by initializing the array to all zero to begin with, e.g.
int seatNo[5][5] = {{0}};
Now any subsequent access to any of the elements of seatNo will succeed because each element has been initialized to zero. As a rule, especially when you are learning C, you will save yourself grief if you simply initialize ALL your variables.
(you will also want to turn warnings on, e.g. -Wall -Wextra, at minimum, so your compiler will warn you when a variable may be uninitialized)
#include <stdio.h>
int main (void) {
int seatNo[5][5] = {{0}};
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
printf (" seatNo[%d][%d] = %d\n", i, j, seatNo[i][j]);
return 0;
}
Example
$ ./bin/initarray
seatNo[0][0] = 0
seatNo[0][1] = 0
seatNo[0][2] = 0
seatNo[0][3] = 0
seatNo[0][4] = 0
seatNo[1][0] = 0
seatNo[1][1] = 0
<snip>

Related

Why different behaviour of same code by different compilers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
This is code written by me where I have to print a single integer denoting the minimum possible capacity of a tram (0 is allowed). It's a problem from codeforces. The answer in CodeBlocks is showing 6 (the right answer) but in codeforces compiler I'm getting another output.
Why is this happening?
#include <stdio.h>
int main() {
int n, i, j, max = 0, sum = 0;
int pssnger_left;
scanf("%d", &n);
int a[n][2];
for (i = 0; i < n; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &a[i][j]); // declaring the value of array
}
}
pssnger_left = a[0][0] + a[0][1];
for (i = 1; i < n; i++) {
sum = pssnger_left - a[i][0];
sum = sum + a[i][i];
pssnger_left = sum;
if (max < sum)
max = sum;
}
printf("%d", max);
}
Input:
4
0 3
2 5
4 2
4 0
Output:
4221555
Answer:
6
Checker Log
wrong answer expected 6, found 4221555
Here is the link of the problem: https://codeforces.com/problemset/problem/116/A
Different compiler, different answer, 99% of the cases is explained by Undefined Behaviour, UB.
In the shown code here it is a[i][i];.
For any i > 1 that is not what you want it to be
and for most high i it illegally accesses beyond a.
-> Undefined Behaviour.
A hint on how I spotted this:
Whenever I see [i][i], actually whenever I see [same][same],
I think "diagonal in a square". And in your code I immediatly thought "What square?", because when seeing int a[n][2]; I thought "Long narrow table." and got a conflict of shapes there.
The problem is not basically with the compiler.
You are doing
sum = sum + a[i][i];
but you have declared a 2D array of n x 2 i.e. int a[n][2]
see in some compilers it shows out of bound because you are accessing an element which is not there in the array
and in compilers it just loops in the already existing array for ex if your array has 5 elements and you are trying to access 6th element then it will go back to 1st index,
so this might be whats happening here.

Why does memcpy change the last element of original array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I encountered a weird bug in this code:
int *a = (int*) malloc(N*sizeof(int)); // allocate array
int i;
for (i=2; i<=N; i++)
{
a[i] = i;
}
int *b = (int*) malloc(N*sizeof(int));
memcpy(b, a, N*sizeof(b));
If I were to print out array a, output = 2,3,...,19 0
Whereas the expected output should have been 2,3,...,19,20.
Copying the array onto b strangely affected the last element.
An array of N elements has valid indexes 0, 1, ..., N - 1. Your final loop round accesses a[N], which is out of bounds and has undefined behaviour.

Filling an Array in C with 0 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Ive got a problem with this code, im trying to add up array1 with array2.
I enter the numbers for array2 by Command line parameters.
When i enter 10 numbers it is working but when i add less than 10 I get an Memory access error.
My question is now: how do i fill up the missing array fields with the number 0? For example : I enter 9 numbers and the 10th field should be 0.
You are not checking how many command line arguments are passed, and when you index into the command line argument array, you will get an out-of-bounds error.
In you addiren function, you should take advantage of the argc that is passed and used that in your for loop limit.
#include <stdio.h>
#include <stdlib.h>
int addiren(int argc, char**argv){
int array_one[10] = {0,1,1,2,3,5,8,13,21,35};
int array_two[10] = {0}; //Quick way to set the array to all zeros
int array_three[10] = {0};
//Set array_two with your cmd-line args, notice the use of argc
for(int i = 1; i<argc && i<=10; i++){
array_two[i-1] = atoi(argv[i]);
}
//Add array_one with array_two to array_three
for(int i = 0; i<10; i++){
array_three[i] = array_one[i]+array_two[i];
}
//Return an int since that's what the function return type requires
return 0;
}
Hope this helps!

Instance of variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a c code
int foo( int *p, int n){
int a[81];
int i,v;
for( i = 0; i < n ; i++){
a[i]=p[i]
if( n == 1 ) return a[0];
v=foo ( a, n-1);
if( v > a[n-1] )
return v;
else
return a[n-1];
}
int main ( void ){
int b[81], i;
for( i = 0; i < 81; i++){
b[i]=rand();
foo(b,81);
return 0;
}
And i need to find out how many instances of variable a will exist( max number) my answer was 81 , but it was wrong and i cant find out what number it should be. How could i determine it?
The main will call the function 82 times and each time the func will call recursively itself 80 times in a loop of decreasing n items.
So altogether it will be 81*81.
EDIT: I didn't notice the return after first iteration so actually it's pretty small number.
Set the number of elements in a to be arbitrarily high.
Build a function to assign elements to a, and only use that function to set elements of a. You could use this function to make sure that you don't attempt to write outside the bounds of a. (Else the behaviour of your program will be undefined and so any results will be meaningless).
Encode a "watermark" static int in that function to record the largest index accessed.
Run your program and note the value of the variable set up for (3).
Declare a global counter - it will be initialized to zero. In the function, at the same scope as 'a' is declared, increment the counter.
Printf() it out at the end of main().

Using a variable in its own declaration in recursion [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Using a local variable in its own initialization usually has no effect but doing it with recursion causes strange values. Why is there undefined behavior in the recursion but not outside of it?
#include <stdio.h>
void recurse(int count);
int main()
{
int j = j + 1; // a weird thing to do but its just 1
printf("%d\n", j);
j = j + 1;
printf("%d\n", j);
j = j + 1;
printf("%d\n", j);
recurse(1);
printf("\n");
}
void recurse(int count){
int i = i + 1; // the really weird part
printf("%d ", i);
if(count < 10)
recurse(count + 1);
return;
}
Output:
1
2
3
32737 1 32737 1 1 1 1 1 1 1
The large numbers are not always the same for each execution.
This is an example of undefined behavior.
Because the value can't be known before it is assigned, you can't predict what will happen. Running the same code on a different machine, or compiled with different settings, can yield different results.
Local variables (not initialized) have indeterminate value in C.
Reading them prior to assigning a value results in undefined behavior.
Nice quote from wikipedia article
In computing, an uninitialized variable is a variable that is declared
but is not set to a definite known value before it is used. It will
have some value, but not a predictable one. As such, it is a
programming error and a common source of bugs in software.
However, it is important to mention that in C, static and global variables not initialized will have the value = 0.

Resources