I have declared an array of length N (suppose). Now, I assign some values to the elements of this array using a loop (the loop variable is used as the array's index). The code's as follows:
int main()
{
int arr[4], j;
for(j=0; j<10; j++)
{
printf("%d\n", j);
arr[j] = 0;
sleep(1);
printf("%d\n\n", j);
}
return 0;
}
I expected the output to be 0 1 2 .. 9. But what actually happened was that j got reset to 0 when the assignment arr[N+2]=0 (arr[6]=0, in this case) was executed in the loop.
What's actually happening here? Am I missing something?
Your array has 4 elements and your index is out of range so you are just stomping on memory.
Given the code here, I'd expect arr[4] to reset the array, but since you mentioned that it's of length N and N+2 is what causes it, there might be some padding in your stack. In any case, when you declare the array and j, they are put on the stack. In your case, j is in a position such that when your index is out of bounds you are accessing the memory where j is.
the behaviour of the code is undefined as it has a bug. arr has a size of 4 but you are indexing past this size with j
Your array is overflowing. You defined it like this with 4 elements:
int arr[4]
But you're trying to assign 10 elements.
j is apparently located immediately after the array, so when you assign arr[6] = 0, you're clearing j.
Related
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
int n;
n++;
printf("n : %d\n", n)'
}
}
The output of the code is 1 2 3 4 5 6 7 8 9. I'm wondering why the variable n in the for loop isn't initialized when the variable declaration is executed.
You're never initializing n to a specific value. C++ will not do this by default when you call int n. Instead, it just reserves an integer sized block of memory. So when you call n++, the program is just grabbing whatever value happens to be in that memory and incrementing it. Since you're doing this in quick succession and not creating new variables in between, it happens to be grabbing the same memory over and over. As #NicolasBuquet points out, compiler optimization may also be responsible for the consistency with which the same chunk of memory is picked.
If you were to assign a value to n, (i.e. int n = 1;) this behavior would go away because a specific value will be written to the chunk of memory assigned to n.
In C++, no variable is initialized with a default value; you must specify one explicitly should you find the need to do so.
The result of your code is really undefined; it is just pure luck that you are getting the numbers 1 through 9 in sequence. On some other machine or implementation of C++, you might get different results.
I'm trying to fill a 4x6 array with random numbers between 0-25 using a for loop inside a for loop. A runtime error occurs after the array is generated- "Stack around the variable "grid" was corrupted. What is causing this to happen?
int grid[4][6];
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 6; x++) {
grid[x][y] = (rand() % 25);
}
}
You're writing out of bounds. Your loop can write, for example, at (5, 3), which is outside the bounds of the array. In order to fix this, use x for the outer loop and y for the inner loop.
I think your indices are backwards, where you have x it should be y and vice versa
As the others have said, you've got the row and column indices backwards. The reason this is a problem is that in C and C++, the 2D array access:
grid[x][y]
is treated as the equivalent pointer expression:
*(grid + (x*COLS + y))
In this case, since C and C++ use row-major ordering, COLS is 6. Additionally, a 2D array is equivalent to a 1D array of size (ROWS * COLS), meaning that in this case you effectively can address elements 0 through 23 of that 1D array.
Now, looking at your loop structure, you can see that given the pointer arithmetic rule, you'll access element 24 (thus clobbering the stack) when x is 4 and y is 0--that is, *(grid + 4*6 + 0), or the 4th iteration of your inner loop.
Switch your loop order (0 <= x < 4 and 0 <= y < 6) and your problem will go away.
int grid[6][4];
You can use gdb, valgrind or anything else to find out the reason of segmentation fault.
I am trying to clear some basic concepts os programming. I preferred doing sorting for this.
Below is my code:
#include<stdio.h>
#include<malloc.h>
#include <string.h>
main()
{
int array[9]={5,2,7,4,7,6,9,8,1,3};
int min,i,j,temp;
for(i=0;i<10;i++)
{
for(j=0;j<=10;j++)
{
if(array[i]<array[j])
{
temp=array[j];
array[j]=array[i];
array[i]=temp;
}
}
}
printf("\n");
for(i=0;i<10;i++)
{
printf("%d ", array[i] );
}
printf("\n");
}
And the output is :
1 2 4 5 6 7 7 8 9 9
which is unexpected. It must be
1 2 3 4 5 6 7 7 8 9
Could some one help me to know why this strange behavior at the end of the array. Why it repeats "9" and Where has "3" lost ?
Also i appreciate if some one tell me name of best sorting (Mostly i have heard of Bubble and quick sort, but why and what is the difference that i don't know). Please dont tell me about in built functions (like qsort() and etc.) because the objective is to clear concepts
You can any language to explain c/c++/ or even algorithm. Thanks
for(j=0;j<=10;j++) will give you undefined behaviour since you're accessing outside the array bounds with your subsequent array[j].
int array[9]={5,2,7,4,7,6,9,8,1,3}; is also unbalanced, you need int array[10] since you have 10 elements in your initialiser list. Better still, let the compiler do the work for you and write int array[]. This is why 3 is currently omitted from your output (notwithstanding the undefined behaviour).
array[9]; i < 10; j <= 10. array index out of bounds. undefined behaviour.
i and j should be checked like i < 9 and j < 9
int array[9]={5,2,7,4,7,6,9,8,1,3};
And you have 10 elements in that array.
You specify an array of 9 elements, and yet you have 10 elements in the initialiser and in your outer loop:
int array[9]={5,2,7,4,7,6,9,8,1,3};
// ^- this is not the last index, but the number of elements!
for(i=0;i<10;i++)
And here you iterate up to index 10, which is the 11th element (index 0 is the first):
for(j=0;j<=10;j++)
//^- when j is 10 this is still true, but there is no array[10]
To fix, change to the following:
int array[] = {5,2,7,4,7,6,9,8,1,3};
// ^- leave empty and let the compiler count the elements
const int array_len = sizeof(array) / sizeof(*array);
// length: ^- whole array / ^- one element
for (i = 0; i < array_len; ++i) {
for (j = 0; j < array_len; ++j) {
Firstly, any code should be added using the code button so that it is formatted properly and easy to read.
Secondly, you're array is too small. It's size is 9 but you have 10 items.
#include<iostream>
void main()
{int v[100],n,k;
cin>>n;
for(int i=0;i<n;i++) cin>>v[i];
k=0;
for(int i=1;i<n;i++)
if(v[i]==v[i-1]) k++;
cout<<k;}
Hey guys, I'm quite new to arrays and was wondering if someone could tell me what this line of code is doing:
int v[100],n,k;
If I'm right in my understanding, I am assuming that we are declaring a array with 100 possible values. However, what is n and k doing here? I saw a similar piece of code before, and it looked like it was programmed in a way such that the value of k would be inserted into our array n number of times.
Is my understanding there correct? I know what the rest of the code is doing but it's just that one line that is confusing.
Here, v is an array of int, while n and k are simple variables (scalars) of type int.
It's just a shorthand for:
int v[100];
int n;
int k;
You may declare severeal variables with the same declare spesifiers in one line. For example
int width, height;
Here there are two variables that are declared as having type int. You can also include an array declarator in the same line.
int width, height, sizes[100];
Here there are three variables, width, height, sizes, that are declared. Variable sizes is declared as an array.
It is equivalent to
int width;
int height;
int sizes[100];
v is an array with 100 elements.
n is the number of elements to look through (probably in the range [0, 100] or we'll run into out of bounds problems trying to accessing v[n] when n > 100)
k is used to count the number of times a value in v is equal to the next value in v.
So lets take an example in some kind of pseudo-code:
v = {0,3,3, ..., n};
// lets for simplicity say that n=3 (i.e. the number of integers I specified)
// the loop will run from 0 to n=3 both the outer and inner loop mind you..
The outer loop starts, i=0, k is set to zero because at this point we don't have any hits.
we start second loop with i=1 (no need to check i=0 since we don't want to check an entry against itself). And every time v[0] is equal to any of the other numbers in the set we will add one to k, so for our example: 0 != 3 and 0!=3 and k=0 will be the case, the program will print 0 and move on.
Second iteration i=1 and v[i] = 3. And the second loop starts to check v[1] against v[2] in this case both happen to be three and so k become one. and the iteration is done. the value 1 is printed and the loop continues.. and so it goes.
I would like to mention as well that the inner loop is creating a local variable int i=1; in the for-loop, I would be a bit careful with that since there might be compilers which can't scope it correctly and choose a different name for the loop index variable of the inner loop, traditionally one might use j but well both i and j could be argued to be bad names, but it's another discussion.
I hope it clears things up a bit.
I have a 2 dimensional array that is filled with info and has 10 indexes. When I run the code below :
for(int studentIndex = 0; studentIndex < numOfStudents; studentIndex++)
{
if(grade[studentIndex][9] > 59){
grade[studentIndex][10] = 1; // 1 stands for pass
}else{
grade[studentIndex][10] = 0; // 0 stands for fail
}
}
grade[studentIndex][10] changes and so does the grade[studentIndex][0] for the next index. the problem is somewhere there because when I cout index 0 before this portion, the value is fine but after this it changes to 1 or 0.
In an array of size 10, the highest index is 9 since indexing begins at 0. I'm guessing that grade[index][10] is basically pushing the pointer forward into grade[index+1][0] and that's why you're seeing this behaviour. You'll need to either enlarge your student info array to 11 or figure out whether you're getting your indexing wrong.
and so does the grade[studentIndex][0] for the next index
This makes it sound like grade is defined as int grade[numOfStudents][10] (or something in that direction). The valid indices for the subarray are only 0 to 9.