Unwanted Output in C Program - c

I have a class project to make an array, declare it's size (add 1) then fill it in numerical, nondecreasing order. After that, I need to declare x, a value to be added to the array in the appropriate spot, so the array is still nondecreasing.
The program builds without error (for once!) but I'm getting some really weird outputs.
#include <stdio.h>
int main (void) {
//Local Declarations
int size;
int ary[100];
int x;
int i;
int j;
//Statements
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("\nEnter digits to fill the array, in numerical order: ");
for (i = 0; i < size; i++) scanf("%d", &ary[i]);
size++;
printf("\nInput x, the value to add to the array: ");
scanf("%d", &x);
while(i <= x && x > ary[i]){
i++;
j = size - 1;
while(j >= i) {
ary[j++] = ary[j];
j--;
}
}
for(i = 1; i < size; i++) {
printf("%d", &ary[i]);
}
return 0;
} //main
When it runs I get:
Enter the size of the array: 3
Enter digits to fill the array, in numerical order: 1
2
3
Input x, the value to add to the array: 4
268634426863482686352
Process returned 0 (0x0) execution time : 7.124 s
Press any key to continue.

I would examine your print function . It looks like you're printing the memory address of that particular array index rather than the value at that spot in the array.

Don't increase the size variable before you iterate through. Then walk backwards through the array, and populate as needed.
for (i = size; i >0; --i)
{
if (ary[i-1] > x)
{
ary[i] = ary[i-1];
}
else
{
ary[i] = x;
break;
}
}
if (i == 0)
ary[i] = x;
Afterwards, you can increase size as you print the output.
I've reproduced your desired output using this array walk.
There are other ways that I would solve this problem in real life, but this works well enough within your existing code.

First things first: what do you EXPECT to see as the output?
Second things first: you aren't clearing out the memory for the array before use. You have garbage values in any slots you aren't using.
Third things first: using GCC I'm seeing at least two warnings without even trying.
test.c:32:15: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("%d", &ary[i]);
test.c:27:14: warning: unsequenced modification and access to 'j' [-Wunsequenced]
ary[j++] = ary[j];

In your printing loop your are not printing the value but your are printing the address of that element. Change the last loop to
for(i = 1; i < size; i++) {
printf("%d", ary[i]);
}
I am not sure why your are printing the array from index 1. But if you want to print whole array you should initialize i to zero in above loop.

Related

How to store values in a array inside other function

I've started learning C. I'm doing functions right now.
In these exercise they want me to ask for a value that means an error. If they input the number 8, it means that it's error "8", if value 6 error is "6"(the error part don't matter). I should call a fuction to store this error and other functio to go trought it and see if any value ("error"), Was stored more than once.
I started by asking for how many errors the user will introduce, soo I could run a loop "N" times to ask for the value.
Then I made a function called aviso(means warning ~ error), to store them in a array.
When the function reaches the last value of "error" it calls other function to count if the numbers are repeated .
My main problem right now is how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
My code is very messy right now, please any suggestions are welcome since I'm clearly very new at C.
Excuse my code I just "try" to translate some names to english.
`
#include <stdio.h>
#include <stdlib.h>
// Function Incomplete since my array is not sotring values
int alertwarning(int array[]){
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
int warning(int num , int n, int count){
int check = count - 1 , array[n];
if(count <= n){
array[check] = num;
}
if(count == n){
alertwarning(array);
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
return 0;
}
int main(int argc, char *argv[]) {
int num, count, n;
printf("|Warning System!|(Only values equal or above 0 are acepted!)\n");
printf("\nIntroduce how many warnings are being stored: ");
scanf("%d", &n);
fflush(stdin);
int array[n];
do{
printf("\nIntroduce a value equal or bigger then 0: ");
scanf("%d", &num);
fflush(stdin);
//system("cls");
if(num < 0){
printf("|Please introduce a valuer equal or above 0!|\n");
system("pause");
}
else if(num >= 0){
count++;
}
warning(num, n, count);
}while( count < n);
return 0;
}
`
I tried to store the array inside the main() and it worked but it was required to do it in other function to complete this exercise. I don't know if the function just don't save the values of the last time it was called.
how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
I tried printf to see where I go wrong with the few knowledge I own. When they are called they work but the next time they are called I think they reset the values of the array.

C Programming How to get results of an mathematical operation stored in a different array?

I am trying to subtract a given number from an array and then store the results in a completely different array. Is it possible to write the code without using pointers?
I am trying to write the code with using for loop and or do/while loop.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
int num[100];
int i ;
int size;
int sub;
int diff[100];
printf("Enter the size of the array: ");
scanf("%d", &size);
for(i=0;i<size; i++){
printf("Enter the element %d :", i+1);
scanf("%d", &num[i]);
}
printf(" Enter the number to substract: \n");
scanf("%d", &sub);
for (i=0;i<size; i++)
{
y = num[i]- sub;
scanf("%d", &diff[y]);
}
for (y=0; y<size; y++)
{
printf("%d", diff[y]);
}
}
After I scan the results, I tried different ways to initialize and store the values in the second array but haven't been successful. What mistake am I making here?
y = num[i] - sub;
This is fine, as it's the result of subtraction for a given source array element.
scanf("%d", &diff[y]);
This doesn't make sense, as it's attempting to read input from the user. Not only that, it's using the result of the subtraction as the index of the destination array.
Just assign the result of the subtraction to the corresponding destination array member:
diff[i] = num[i] - sub;
In your question, you try to scan the value to another array, but the correct form is to assign the value in the new array position.
For example, in your first for loop use the i variable as the position and assign num[i] - sub on diff[i]:
for (i = 0; i < size; i++)
{
diff[i] = num[i] - sub;
}
instead of:
for (i=0;i<size; i++)
{
y = num[i]- sub;
scanf("%d", &diff[y]);
}

C program displays garbage value while taking user input using scanf

I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");

Defining malloc array size with scanf and initialising

I'm trying to create a program that asks the user for a size of an array, then asks the user to populate it.
Whenever I launch the program, the "Element %d" printf displays the %d as a large number instead of 1.
If I continue the program after entering the value into the array, the debugger crashes. What's happening here? Did I accidentally place the address in the array position? Thanks
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int elements = 0;
printf("How many Elements will you enter?");
scanf("%d", &elements);
int* elementArray = malloc(sizeof(int) * elements);
int i = 0;
while (elementArray[i] != '\0')
{
printf("Element %d: ", elementArray[i]);
scanf("%d", &elementArray[i]);
i++;
}
free(elementArray);
return 0;
}
EDIT: Reading the comments, I meant printf("Element %d: ", elementArray[i]); was supposed to print one during the first loop. Though I should edit the code to be elementArray[i] + 1 so it doesn't print "Element 0" instead of Element 1. Apologies for the barebones code, it's half finished, I wanted to solve this problem before finishing it off. Will work on the solutions given now. Thanks for the help
EDIT2: Thanks to all of you, especially Sharuya! Here's my finished code.
void printArray(int* elemArray, int elements)
{
printf("The Array contains: ");
for (int k = 0; k < elements; k++)
{
printf("%d,\t", elemArray[k]);
}
}
int main(void)
{
int elements = 0;
printf("How many Elements will you enter?");
scanf("%d", &elements);
int* elementArray = (int *)malloc(sizeof(int) * elements);
int input = 0;
for (int j = 0; j < elements; j++)
{
printf("Element %d: ", j + 1);
scanf("%d\n", &input);
*(elementArray + j) = input;
}
printArray(elementArray, elements);
free(elementArray);
return 0;
}
Only issue now is, between the "Element 1: " and "Element 2: " printf, I get a blank line, that allows me to enter a number, upon submitting, it continues as normal. If I submit an array with 5 elements, It asks me for 6 elements, and only 5 appear... What's happening here?
while (elementArray[i] != '\0')
This check is the problem
malloc gives no guarantee that the memory initialized will be zero filled. Hence your loop may cross over the allocated memory and try to read memory that your program is not supposed to read (hence resulting in a crash)
If it's zero filled your code will never enter the loop
What you need is
while (i < elements)
Also printf should come after scanf for any meaningful result. If you want to just get the index that you are about to enter use printf("Element: %d", i) instead of elementArray[i]
A couple of questions, for you to ask:
What if the user enters a negative value?
What if the user enters 0 ?
What if the user enters a very large value?
Did the array allocation succeed?
What is in my array after it is allocated?
If my array size is 0, will elemenArray[0] be valid?
Should I use a for loop, like everyonbe else does for walking through my array?
Just asking yourself these questions will fix this program in no time, and will get you through half of the next one you'll write.
You have more problems than the fact that you print something else than the index.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int elements = 0;
printf("How many Elements will you enter? ");
if((1!=scanf("%d", &elements))||(elements<1) ) // check return value, always a good idea
{ printf("Reading number failed.\n");
return 1;
}
int* elementArray = malloc(sizeof(int) * elements);
int i = 0;
while ( (i<elements) // use the number you asked for to avoid writing beyond array
&& ((0==i) || (0 != elementArray[i-1]))) // stop when previously entered value is 0
{
printf("Element %d: ", i+1); // print the index
// instead of the non-initialised value
if(1!= scanf("%d", &elementArray[i]))
{
printf("Reading value failed!\n");
free(elementArray); // cleanup
return 1;
}
i++;
}
if (i<elements)
{
printf("Stopped early because 0 was entered.\n");
}
free(elementArray);
return 0;
}
First you need to know that malloc() function dynamically allocates memory according to the size calculated (with the help of sizeof() ) and returns the address of this memory location.
However this address is not associated with any data type i.e. only a void* pointer can store this address of an incomplete data type.
Thus instead of mentioning
int* elementArray = malloc(sizeof(int) * elements);
mention and use typecasting to it
int* elementArray = (int *)malloc(sizeof(int) * elements);
As per your code, elementArray is a pointer which will store the address of an integer
int *elementArray;
printf("Element %d: ", elementArray[i]);
Thus the above line will actually print the address pointed to by the pointer and not the index since incrementing a pointer is same as
elementArray stores the base address.
i.e elementArray++ is equal to elementArray+1 == elementArray[1] will point
to the next memory location after 4 bytes.(since integer is stored in 4 bytes)
I have modified your code correcting your mistakes
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int elements = 0;
printf("How many Elements will you enter?");
scanf("%d", &elements);
//the below statement actually allocates contiguous block of memory equal
//to no of elements and the pointer points only to first element.
//Incrementing it will point to next element
int* elementArray =(int *) malloc(sizeof(int) * elements);
//typecasting of void* pointer to int*
int i = 0,elm;
for(i=0;i<elements;i++)
//Since u know iterations will be equal to no of elements it is better to use for loop
{
printf("Element %d: ", i);
scanf("%d", &elm);
*(elementArray+i)=elm;
//Storing the data in elm and making the pointer point to next free
//dynamically allocated block of memory and using * operator the value at
//this location is accessed and storing elm value in it
}
for(i=0;i<elements;i++)
printf("%d",*(elementArray+i));
free(elementArray);
return 0;
}
This code works and I hope it make things clear !!!

My program crashes, I don't understand why it does not even reach the first printf

My program is supposed to order a list of numbers inputed by the user, but it crashes even before reaching the first printf. My compiler makes 2 warnings, but I don't see the issue. I haven't studied pointers yet, so I didn't want to use them. Here are the messages:
In function `selection_sort':
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
In function `main':
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
.
#include<stdio.h>
int selection_sort(int n, int v[n])
{
int high = v[0];
int i;
for(i = 0; i < n; i++)
high = high < v[i]? v[i] : high;
if(n - 1 == 0)
return;
v[n - 1] = high;
n -= 1;
selection_sort(n, v[n]);
}
int main(void)
{
int n, i;
int v[n];
printf("Enter how many numbers are to be sorted: ");
scanf("%d", &n);
printf("Enter numbers to be sorted: ");
for(i = 0; i < n; i++)
scanf("%d", &v[i]);
selection_sort(n, v[n]);
printf("In crescent order: ");
for(i = 0; i < n; i++)
printf("%d ", v[i]);
getch();
return 0;
}
Your program is using a variable length array, a feature that was added in C99.
However, you declare its size based on an uninitialized variable. What did you believe would happen there?
In C, variables declared inside functions are NOT set to 0. They are not set to anything. They pick up whatever value was left on the stack or in the register that they are assigned.
I believe that your program is crashing because n in int v[n] is a ridiculously big number and v is trying to use too much memory.
You can probably fix this by moving your array declaration below the scanf that reads in n.
You need to pass v, not v[n] to the function selection_sort. v is the array, v[n] is actually an out of bounds element of v.
the line should be selection_sort(n, v);

Resources