#include<stdio.h>
int main() {
int i;
int vector[5]={6,17,28,39,410},*r; //variables declaration
r=(int*)&vector; //pointer declaration
for (i = 0; i<5;i++){ //print the array in using a loop
printf("%d ",vector[i]);
}
printf("\n\n");
for(i=0;i<5;i++){ //print the array in reverse order using a loop
vector[i] = *(r+4-i); //it should be from the last to the first but it prints it
printf("%d ",vector[i]); //differently, see below
}
return 0;}
It should be:
6 17 28 39 410
410 39 28 17 6
but it results in:
6 17 28 39 410
410 39 28 39 410
the last two should be 17 6
You are overwriting the data you're trying to read, before reading it.
Just write out the steps your code is taking manually, and you'll see it.
To do reversal in-place, you must swap values around, to avoid overwriting.
Also note that the name of an array evaluates to a pointer to the first argument, in the proper context. So this:
r=(int*)&vector;
is much better written as just:
r = vector;
You should really avoid casts, and your cast is completely unnecessary.
try this:
#include<stdio.h>
int main() {
int i;
int vector[5]={6,17,28,39,410},*r; //variables declaration
r=(int*)&vector; //pointer declaration
for (i = 0; i<5;i++){ //print the array in using a loop
printf("%d ",vector[i]);
}
printf("\n\n");
for(i=0;i<5;i++){ //print the array in reverse order using a loop
//it should be from the last to the first but it prints it
printf("%d ",*(r+4-i)); //differently, see below
}
return ( 0 );
}
In your code you are changing the first two values. So first two steps Your array
will be like this.
410 39 28 39 410
After that loop continues it will get that replaced value. You can store the replaced value in the another array.
for(i=0,j=4;i<j;i++,j--){
temp=vector[i]; // storing the value in temporary variable
vector[i] = r[j];
r[j]=temp; // assigning the value .
}
for ( i=0; i < 5 ; i ++ )
printf("%d\n",vector[i]);
Related
The level is basic so bear with me. There are a few similar topics but didn't find my luck there. What I'm trying to do is to find max element in a row and then put it in the place of last element of the same row, while the last element to be put in the place of the max one the program found.
So I've got this code in C, it's supposed to print the original array, do the magic and then print the modified array. It does find the max element in 1st row, puts it in the last place of the same row, but doesn't do the switch - the last element doesn't hop in the place of max element's. I know I did something dumb and plain simple, but I just can't find where the mistake is. Any help highly appreciated!
int main()
{
int a[3][4]={23,32,45,12,53,75,38,72,14,37,42,82}, i, j, t, l, max=a[1][0];
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<4;j++){
printf("%d ", a[i][j]);
}
}
for(l=0;l<4;l++){
if(a[1][l]>max){max=a[1][l];}
}
t=a[1][3];
a[1][3]=max;
max=t;
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<4;j++){
printf("%d ", a[i][j]);
}
}
return 0;
}
And here is what it returns (original array):
23 32 45 12
53 75 38 72
14 37 42 82
(modified array):
23 32 45 12
53 75 38 75
14 37 42 82
You also need to store the position of max:
int max_pos = 0; //same as the initial max - a[1][0]
for(l=0;l<4;l++){
if(a[1][l]>max){max=a[1][l]; max_pos=l;}
}
Then when you switch them:
t=a[1][3];
a[1][3]=max;
a[1][max_pos] = t;
I assume you are aware this only happens for the second row. If you want to do it for all rows, you'll have to store the positions in an array.
This code:
#include <stdio.h>
#define SIZE 10
int main(){
int a[SIZE]={2,6,4,8,10,12,89,68,45,37};
int pass;
int i;
int hold;
int dim=10;
printf("Data items in original order\n");
for(i=0; i<SIZE; i++){
printf("%4d", a[i]);
}
for(pass=1; pass<SIZE; pass++){
for(i=0; i<dim; i++){
if(a[i]>a[i+1]){
hold=a[i];
a[i]=a[i+1];;
a[i+1]=hold;
}
}
dim--;
}
printf("\nData items in ascending order\n");
for(i=0; i<SIZE; i++){
printf("%4d", a[i]);
}
printf("\n");
return 0;
}
gives me this error:
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10-98850560 12 37 45 68
*** stack smashing detected ***: ./prog terminated
Why? I don't understand. Please explain it to me. Thank you very much. I just don't get it. I don't understand. Please help me. I don't know what to do. Please.
The problem is with this line:
if(a[i]>a[i+1])
i can go upto dim-1 and dim is 10. So when i becomes 9, the above expression becomes
if(a[9]>a[10])
You will be accessing the 11th element of an array which contains only 10 elements and thus you will access an out-of-bounds memory address. This is undefined behaviour.
From wiki:
The behavior of some programming languages—most famously C and C++—is undefined in some cases. In the standards for these languages the semantics of certain operations is described as undefined. These cases typically represent unambiguous bugs in the code, for example indexing an array outside of its bounds.
stack smashing detected means there is a buffer overflow in the stack, you basically went out of the bound of your array.
int dim=10; dim is 10
for(pass=1; pass<SIZE; pass++){ <<< First loop, dim is still 10
for(i=0; i<dim; i++){ <<< i < 10
if(a[i]>a[i+1]){ <<< Last loop : i=9
hold=a[i];
a[i]=a[i+1];;
a[i+1]=hold;
}
}
dim--;
}
i=9 a[i+1] => a[10] which is out of bound
Hope that helps~~
In statement : if(a[i]>a[i+1]) when i = 9 (max 9 in this for loop), that time you are comparing a[9]>a[10] but you defined array up to a[9].
Modify that for loop as:
for(i=0; i<dim-1; i++)
if(a[i]>a[i+1])
This is the code. Why am I facing this error and what source of information should I refer so as to rectify such errors so that I get to know 'If I do this that way, I will get 'x' error'
#include<stdio.h>
void main()
{
int i,avg,sum;
int marks[30]; // Array declaration
for(i=0;i<31;i++)
{
printf("Enter Marks:");
scanf("%d",&marks[i]); // Stores data in Array
}
for(i=0;i<31;i++)
sum=sum+marks[i];
avg=sum/30;
printf("Average marks of student \t %d",avg);
}
Whenever you declare a variable in a function it allocates memory on the stack. The stack is a reserved memory area for doing temporary data manipulation within the function. Now in your code you declared 3 ints and one array of ints with 30 slots. In your for loop you are putting 31 ints into 30 slots; from 0 thru 30 are 31 numbers. The last number is being put beyond the 30th slot and therefore "smashing" into the next spot on the stack, in other words overwriting it. The solution would be to change you for loop to for(i=0;i<30;i++).
You have declared an int type array as [30] and have tried to assign 31 values to it. Please note that the array starts from 0. So the for loop should be as mentioned below.
for(i=0;i<30;i++)
Hence the issue, Please change the for loop and rest are all fine in your code. Thank you. :)
#include<stdio.h>
void main()
{
int i, avg, sum=0;
int marks[30]; // Array declaration
for (i = 0; i<30; i++)
{
printf("Enter Marks:");
scanf("%d", &marks[i]); // Stores data in Array
}
for (i = 0; i<30; i++)
sum = sum + marks[i];
avg = sum / 30;
printf("Average marks of student \t %d", avg);
}
I am trying to create an index array that will store the location of every ',' that is read in from a file. I have written the code and it seems to work but for some reason stops after exactly 1 ',' past the first line in the file.
What in the world is causing it to stop I cant figure it out. It just gives zeros after the first couple indexes.
#include <stdio.h>
#include <stdlib.h>
void getCommaIndex(int n,char table[],int index[]){
int i;
int p = 0;
for(i = 0 ; i < n ; i++){
if(table[i] == ','){
index[p] = i;
p++;
}
}
}
int main()
{
char table[100000];
int index[5000];
int i;
FILE *fp;
fp = fopen("C:/Users/Chris/Desktop/Open Frameworks/apps/myApps/bin/data/tableshort.csv","r");
while( !feof(fp)){
fgets(table,"%s",fp);
printf("%s",table);
getCommaIndex(5000,table,index);
}
for(i = 0 ; i < 11 ; i++){
printf("%d ",index[i]);
}
Output will look something like:
7 11 20 35 40 59 62 67 0 0 0 0 0 0
I just changed:
fgets(table,"%s",fp);
to:
fgets(table,5000,fp);
and everything worked.
See: http://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
Also, your code in your question gave me this message in my compiler: warning: passing argument 2 of 'fgets' makes integer from pointer without a cast. Treat warnings as errors as much as you can.
Instead of reading the entire file at once, you could try reading a single line at a time. Also, in your getCommaIndex function table[] is 100000 but you only iterate over the first 5000 indices. It is not clear to me but it seems like you value for n should be 100000 so you loop over the entire table array.
I have this simple problem to which I am trying to write a solution, in C.
If an array arr contains n elements, then write a program to check
if arr[0] = arr[n-1], arr[1] = arr[n-2] and so on.
And my code looks like this-
#include<stdio.h>
int main()
{
int arr[10],i=0,j;
int k=0;
printf("\n Enter 10 positive integers: \n");
for(k=0;k<=9;k++)
scanf("%d",&arr[k]);
while(i<=9)
{
for(j=9;j>=0;j--)
{
if(arr[i]==arr[j])
{
printf("\n The array element %d is equal to array element %d\n", arr[i],arr[j]);
}
i++;
continue;
}
}
return 0;
}
On entering this input-
Enter 10 positive integers:
10
20
30
40
50
60
40
80
20
90
The output I get is-
The array element 20 is equal to array element 20
The array element 40 is equal to array element 40
The array element 40 is equal to array element 40
The array element 20 is equal to array element 20
Now, there are two problems with this code-
As you can see, the program prints out matching array elements twice. This is because, the way I've structured the program, once the variable i loops through the array from the first to last element, and then j loops through from the last to first element. So each prints out the matching array element once, leading to two sets of values.
My second question is- In my code, I've hard-coded the length of the array in the for loops(0 to 9 for an array of 10 elements). What change can be done so that the length of the array, as entered by the user, can directly be used in the for loops?
I've read that, in C, array dimensions(when declaring) cannot be a variable. So, a declaration like this(which was my first thought) wouldn't work-
int n; // n is no. of elements entered by the user
int arr[n];
I'm a newbie to programming, so my apologies if the question sounds/is too simple, low-quality.
Thank You.
1)You can traverse the array for half times for getting the prints only once. Instead of for(j=9;j>=0;j--) you can use for(j=9;j>=9/2;j--).
2)
int n;
int arr[n].
Recent Compilers support this statement. If you don't like to use this, you can go for dynamic memory allocation for the array.
My second question is- In my code, I've hard-coded the length of the array in the for loops(0 to 9 for an array of 10 elements). What change can be done so that the length of the array, as entered by the user, can directly be used in the for loops?
Use dynamic memory allocation. Use malloc().
So code will be
{
int num_elements;
int* arr;
printf("Enter number of elements\n");
scanf("%d", &num_elements);
arr = (int *) malloc(num_elements * sizeof(int)); // Use this 'arr' for holding input data from user
// Your remaining code comes here
free(arr); // Free the pointer in the end of program
}
the variable length creation works for me:
#include<stdio.h>
int main(){
int a, i;
scanf("%i", &a);
int blah[a];
for (i = 0; i < a; i++){
printf("/n%i", blah[a]);
}
}
The other way would be to create the maximum length array and than simply use first n elements.
As the previous answer states it is up to you to make sure you are checking each element only once therefore stopping at the element n/2. It is probably important that n/2 is rounded to the closest smaller integer, so at first glance odd numbers of arguments may be differently handled. But as it is omitting only the middle element it is identical to itself.
For your first query
for(i=0;i<n/2;i++)
{
if(a[i]==a[n-(i+1)])
{
printf("\n The array element %d is equal to array element %d\n",a[i],a[n-(i+1)]);
}
}
For your second query you can use condition i<(n/2) (which runs the loop (n/2)-1 times) For your case where n = 10 it will run from 0 to 4.
If you want to loop from 0 to 9 you can use
for(i=0;i<n;i++)
For making array of n elements where n is a variable either make an array of elements that is always greater than n or do it by making a dynamic array.
http://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.html
corrected:
#include<stdio.h>
int main()
{
int i=0, size; // size of array
int k=0; // counter
printf("enter size of array\n");
scanf("%d", &size); // ask user for desired size
int *arr = malloc(size * sizeof(int)); // allocate memory for array
printf("\n Enter 10 positive integers: \n"); // fill your array of size size
for(k=0;k<size;k++)
scanf("%d",&arr[k]);
k = 0; // reset this counter
for(i=0; i<size/2; i++) // check only for half of it
{
if(arr[i] == arr[size-i-1]) // try it with paper and pincil
{
printf("match arr[%d]=arr[%d]=%d\n", i,size-i-1, arr[i]);
k++;
}
}
if(k==0) printf("No matching");
return 0;
}