I'm trying to create an array which has size depended upon input elements count. After that I want to print it but I'm getting very strange outputs.
int main(void)
{
int input_arr;
int i,size=0;
int arr[size];
while(input_arr!=-1){
printf("enter positive int");
scanf("%d",&input_arr);
arr[size]=input_arr;
printf("%d",arr[size]);
for(i=0;arr[i]!='\0';i++){
printf("%d ",arr[i]);
}
size+=1;
}
return 0;
}
33 3 3 3 3 3 6487488 enter positive int3.
It gives output like this and after a while it stops taking elements. I could not recognize where am I doing wrong.
In C the size of the array is fixed the moment you define it. Increasing the size variable does not increase the array size. Therefore you immediately get a buffer overflow the moment you read the first element. You can instead declare a large array like this:
static const int maxSize = 4096;
int arr[maxSize];
int main(void)
{
int i, size=0;
while(size < maxSize){
printf("enter positive int");
scanf("%d", &arr[size]);
++size;
for(i=0; i < size; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
return 0;
}
Alternatively you can use malloc and realloc to grow the array dynamically.
Related
Just getting to learn C better and I'm playing with arrays.
I would like to enter my phone number into an array like this:
#include <stdio.h>
int main()
{
int phoneNum[10];
for (int i = 0; i < sizeof(phoneNum); i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
return 0;
}
This seems to fail as it keeps asking me for a new digit. So I tried to print the size of the array:
int phoneNum[10];
printf("%lu", sizeof(phoneNum));
which incredibly gives me the result of 40 even though I initialized it to be 10 (?).
I have three questions:
Why is the result 40 and not 10 in sizeof(phoneNum) ?
How can I add elements in an array successfully with scanf in the above manner?
If the above manner is silly, is there a better, more efficient way to do this? For example directly enter 10 digits into an array? I can of course use scanf("%d%d%d...", digit1, digit2, digit3, ...) but I would like a generalized way, using the size of the array (say I don't know it and it's passed from another function)
sizeof(phoneNum) returns 10 * sizeof(int). The sizeof(int) value appears to be 4 for your system.
#include <stdio.h>
int main()
{
int phoneNum[10] = {0};
const size_t size = sizeof(phoneNum) / sizeof(int);
for (int i = 0; i < size; i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
for(int i = 0; i < size; ++i)
{
printf("\r\n %i \n", phoneNum[i]);
}
return 0;
}
sizeof(phoneNum) will return number in bytes, not length of array.
after the includes you could make a define like #define SIZE 10 and use SIZE like if it was a constant.
#include <stdio.h>
#define SIZE 10
int main()
{
int phoneNum[SIZE];
for (int i = 0; i < SIZE; i++)
{
//Do Something
}
}
Take into account the fact that strings should end with null terminated character (\0) so the size of the string have that space available.
I'm trying to write a program which includes an array that filled by user and find a value in it which specified by user then print if it found and count of that number in array.But it works only for first element of array.My code is below:
`void searchh(int arr[],int search,int number,int counter);
int main()
{
int number,search,i;
int counter=0;
printf("How many numbers will you enter?");
scanf("%d",&number);
int array[number];
for(i=0;i<number;i++){
printf("Please enter the %d. element of the array:",i+1);
scanf("%d",&array[i]);
}
printf("Please enter the number that you're looking for:");
scanf("%d",&search);
searchh(array,search,number,counter);
return 0;
}
void searchh(int arr[],int search,int number,int counter){
int i,c;
int key=search;
int num=number;
counter=0;
int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];
for(i=0;i<arrsize;i++)
{
if(arr[i]==key)
{
arrayent[counter]=i;
counter++;
}
}
printf("The number that you're looking for which is %d is found %d times.\nLocations:",key,counter);
if(counter>0){
for(c=0;c<sizeof(arrayent)/sizeof(int);c++){
printf("%d\n",arrayent[c]);
}
}
else
printf("Number doesn't exist!!");
}`
And Outputs:
Thanks for your helps.
int arrsize=(int)(sizeof(arr)/sizeof(int));
This already doesn't do what you think it does. sizeof(arr) - could be 4 if size of pointer is 4 bytes. In other words you can't check array size like that inside function, arr decays to pointer of first element of array. Hence sizeof(arr) will return size of pointer which could be 4 or 8. You need to pass the number of elements of the array to the function as parameter - which is number in your case.
This:
int arrayent[(int)(sizeof(num)/sizeof(int))];
is also strange. num is int. sizeof(num) and sizeof(int) will be same - and division will give you 1.
IMO these two lines
int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];
should just go as
int arrsize = number;
int arrayent[number];
PS. Also try to use a debugger to help you with some kind of issues.
I'm trying to calculate the size of the file . The process I've followed is to read the file and store it in an array and calculate its size. However,I really don't know ... I tried n number of ways..I've to pass this size as an attribute to the frequency function.along with the name of the array.
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int ??????, int x)
{
int count = 0;
int u;
for (u = 0; u < ??????; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int r = 0;
int num;
int theArray[100];
int there[100];
int n;
int g;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",(integers[i]));
there[r] = integers[i];
i++;
}
//printf("%d",there[r]);
//printf("\n%d",file);
//fclose(file);
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,????????,x);
getch();
fclose(file);
}
?????? is the size of the integer array from where i read the file and stored it.
I could not find a way to calculate the size of the array into which i copied my file. My idea is to calculate the frequency of a number in that file and calculate the probability of it's occurrence and thereby calculating entropy..Suggestions please!
I don't know why you are initializing so many variables and some of them with awkward names like ??????.
Your main problem is that the call to function should be
frequency(integers, i, x);
Your code with the awkward irrelevant parts removed will look like
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int number, int x)
{
int count = 0;
int u;
for (u = 0; u < number; u++)
{
if ( theArray[u]==x)
count++;
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int num;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",integers[i]);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf(" %d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,i,x);
getch();
fclose(file);
}
There are a lot of parts of this code that don't make sense, but I assume it is your debugging trying to figure out what is wrong. The answer to your specific question is:
For each value read from the file you set integers[i] to the value and then increment i. Thus i is the count of items in integers. You then pass integers to frequency(), so i should be passed to the second parameter as the count.
Note that if there are more than 100 values in the file, you will over index integers and cause unpredictable behavior.
To calculate length of array:
int len= sizeof(arr)/sizeof(arr[0]);
It will give length of array without looping.
I have the following source and when I execute it the values are getting their signs changed. I am not able to find out where I am going wrong. Any suggestions is helpful
Code
#include <stdio.h>
#include <stdlib.h>
int arrsort(int *arr, int size);
int display(int *arr, int size);
int main()
{
int s_o_1=0, s_o_2=0;
int i; //index for arrays
int a[s_o_1],b[s_o_2];
printf("enter the size of the first array\n");
scanf("%d",&s_o_1);
printf("Enter the values of the first array\n");
for (i=0;i<s_o_1;i++)
{
scanf("%d",&a[i]);
}
printf("enter the size of the second array\n");
scanf("%d",&s_o_2);
printf("Enter the values of the second array\n");
for (i=0;i<s_o_2;i++)
{
scanf("%d",&b[i]);
}
//sort the first array
arrsort(a,s_o_1);
printf("The sorted first array is\n");
display(a,s_o_1);
//sort the second array
arrsort(b,s_o_2);
printf("The sorted second array is\n");
display(b,s_o_2);
}
int arrsort(int *arr, int size)
{
int temp; //for holding the temp value
int i; //for indexing
int j;
for(j=0;j<size;j++)
{
for(i=0;i<size;i++)
{
if(arr[i]>arr[i+1])
{
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
}
int display(int *arr, int size)
{
int i; //array index
for (i=0;i<size;i++)
{
printf("%d\t",i);
}
printf("\n");
for (i=0;i<size;i++)
{
printf("%d\t",arr[i]);
}
printf("\n");
}
Output
enter the size of the first array
5
Enter the values of the first array
1 5 -10 -15 3
enter the size of the second array
5
Enter the values of the second array
-3 -5 15 9 10
The sorted first array is
0 1 2 3 4
-15 -10 3 5 10
The sorted second array is
0 1 2 3 4
-15 -10 -5 -3 9
The problem is the array declaration:
int s_o_1=0, s_o_2=0;
int i; //index for arrays
int a[s_o_1],b[s_o_2];
The arrays are probably declared with size 0. Either declare with an appropriate maximum size, or declare after reading the sizes for the arrays.
Your code has undefined behaviour. In this line:
int a[s_o_1],b[s_o_2];
It declares arrays with zero size. When later get values for s_o_1 and s_o_2 the array size won't change. So all your reads & writes lead to undefined behaviour.
C standard requires array should be of non-zero length.
The way you reserve memory is not correct int a[s_o_1],b[s_o_2];
You must use int *a, *b; and later after scanf("%d",&s_o_1); you need to do something like a = (int*)malloc(sizeof(int)*s_o_1);
The same goes to allocating memory for b.
Also bubble sort alghorithm should be something like bellow
for(j=0;j<size - 1;j++)
{
for(i=j + 1;i<size;i++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
I am reading C Primer Plus these days and here is the code I wrote for the programming practice No.4 in Chapter 10, finding the index of the largest number in a double-typed array. I used variable length array in order to manually specify the array size:
#include <stdio.h>
int findmax(const double array[], int s);
//find the index of the largest number in the array
int main(void)
{
int size = 0; //size of the array
int index = 0; //index of the largest number
double num[size]; //the array holding double-type numbers
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter %d numbers: ", size);
for (int i = 0; i < size; i++)
scanf("%lf", &num[i]);
index = findmax(num, size);
printf("The index of the max number in the array is: %d\n", index);
return 0;
}
int findmax(const double array[], int s)
{
int index = 0;
double max = array[0];
for (int i = 0; i < s; i++)
if (array[i] > max)
{
max = array[i];
index = i;
}
return index;
}
This piece of program compiles normally, using MinGW (assume the program file name is prog.c):
gcc prog.c -o prog.exe -std=c99
The program works fine when the "size" varialbe is less than 5. But when I enter 6 or larger numbers for the "size" varialbe, the program crashes during runtime.
Loosely translated, the error message is:
the memory 0x00000038 used by 0x77c1c192 could not be "written".
I tried to eliminate the use of variable length array, the program seems to work fine. But I still couldn't get where is wrong with the original one.
Size is 0 when you allocate num. You get access violation later on because you try to acces num[0] which has not been allocated.
EDIT: I propose to use dynamic memory or declare num after size is read.
Put the statment double num[size]; after taking input of size from user for size variable.
The program works fine when the "size" varialbe is less than 5. This is the most dangerous kind of programming error -- one that appears to work fine but really does not. By writing into your array, you're immediately writing into memory that is claimed for some other purpose, because your array has no length at all. You cannot just change the size of your array by changing the size variable after the fact.
One option is to determine size before you declare the array. Another is to perform a dynamic allocation using new, but you'll get into that in several chapters, I'm sure.
int size = 0; //size of the array
int index = 0; //index of the largest number
double num[size]; //the array holding double-type numbers
printf("Enter the size of the array: ");
scanf("%d", &size);
When you first declare num array, it's size would be zero, as this is the value of size when that line is executed, although you maybe reading the value of size again later on.
When you are creating an array, the size of the array will be zero as already pointed out by others. So, when you try to fill elements into the array, there is no memory available and it overwrites into some other memory eventually leading to a memory corruption.
You can rewrite the code as below to avoid the problem.
int size = 0; //size of the array
int index = 0; //index of the largest number
double *num = NULL; //Change it to a pointer
printf("Enter the size of the array: ");
scanf("%d", &size);
num = malloc(size * sizeof(double));
if(NULL == num)
{
printf("Malloc Failed\n");
return 0;
}
printf("Enter %d numbers: ", size);
for (int i = 0; i < size; i++)
scanf("%lf", &num[i]);
or
int size = 0; //size of the array
int index = 0; //index of the largest number
printf("Enter the size of the array: ");
scanf("%d", &size);
double num[size]; //Now, num will have proper size
printf("Enter %d numbers: ", size);
for (int i = 0; i < size; i++)
scanf("%lf", &num[i]);
Here's a link to an informative article about C99's variable length arrays which talks about some potential problems which C99's variable length arrays can cause.
As others have suggested, using malloc() is the correct way to do this. Other than that, you can just make your array an arbitrary large size, and stop accepting input once it's full.