This question already has answers here:
Length of array in function argument
(9 answers)
Closed 7 years ago.
I have this piece of code:
#include <stdio.h>
int average(int array []);
int main () {
int num_array[];
int x = 0;
while(num_array[x] != -1){
printf("Enter a number\n");
scanf("%d",&num_array[x]);
x++;
}
printf("%d\n", average(num_array));
return 0;
}
int average(int array[]){
int i;
int total_size = (int)sizeof(array);
int sum = 0;
for(i = 0; i < total_size; i++){
sum = sum + array[i];
}
return sum/total_size;
}
But i get an error at compile time, because i'm not initialising the array. However i can't do it, since i don't know it's size.
How can i solve this ?
You can't declare an array like
int num_array[];
in C except when it is a parameter of a function. You must have to specify the size.
This is actually a surprisingly tricky problem in C unless you're using an array library. What you're actually talking about is a growable array. For what you're trying to do, you start with an initial size, say 10, using malloc() and as the inputs grow, you have to realloc() the array to a larger size. Generally, you double the size of the array every time the limit is hit. If you're a beginning C programmer, this is probably too much to take on. I would set a fixed limit, and enforce it by not accepting any more input after the limit is hit. Given that you can comfortably allocate 1000's of ints and a human won't want to type that much, you can easily make a practical limit ahead of time and declare the array as such:
int num_array[1000];
You need to provide the size of the array here: int num_array[];.
If you are working with a structure of unknown size, you could:
Ask the user how many numbers are going to be entered (not really practical, but might suffice if your case is a trivial one).
Initialize it with a default size, say 10 and then if you need, create larger arrays and copying your current data to the new one.
Or else, you use a linked list like data structure and create new elements as you go along, thus allowing your list to grow as much as you need it to be.
Related
I don't know how to ask this question as it was little confusing to me. i was having a problem with this code
#include <stdio.h>
#include <stdlib.h>
#define ull unsigned long long
#define SIZE 1000000001
#define min(a,b) ((a<b?a:b))
#define max(a,b) ((a>b?a:b))
int solve(void) {
// unsigned *count = malloc(sizeof(unsigned) * SIZE);
int k;
scanf("%d", &k);
unsigned count[SIZE];
for (ull i = 0; i < SIZE; i++){
count[i] = 0;
}
return 0;
}
int main(void){
unsigned t;
if (scanf("%u", &t) != 1) return 1;
while (t-- > 0){
if (solve() != 0) return 1;
}
}
This code for me is giving segfault.
What my observation is
it is running fine until it is in solve function.
on calling solve function it is giving segfault.
It has nothing to do with scanf("%d", &k) as by removing this line gives the same error
But if we decrease the SIZE value it will run fine.
Other thing which i can do is instead of creating an array on stack i can use heap and this is working fine.
If i only declare array count in solve function instead of taking k as input and initializing all the values of array count to 0. i am not getting any segfault
So i have some questions regarding this.
Is this due to memory limitation to array or because of memory limitation for a stack frame for the function solve (or possibly another reason which i can't find).
If this is due to any kind of memory limitation than isn't it is too low for a program?
How compiler checks for such errors as adding any kind of print statement won't run before array declaration as i am getting segfault when program reaches solve. So compiler somehow knows that their is a problem with code without even getting there.
and specifically for the 6th point, as per my knowledge when declaring array it reserves memory for the array. So by initializing it i am doing nothing which will increase the size of array. So why i am not getting any kind of error when declaring array while i am getting segfault when i am initializing all those values in array
Maybe i am seeing it in totally wrong way but this is how i think it is, So please if you know any reason for this please answer me about that too
It depends on your operating system. On Windows, the typical maximum size for a stack is 1MB, whereas it is 8MB on a typical modern Linux, although those values are adjustable in various ways.
For me it's working properly check with other platform or other system.
I want to get a variable from user and set it for my array size. But in C I cannot use variable for array size. Also I cannot use pointers and * signs for my project because i'm learning C and my teacher said it's forbidden.
Can someone tell me a way to take array size from user?
At last, I want to do this two projects:
1- Take n from user and get int numbers from user then reverse print entries.
2- Take n from user and get float numbers from user and calculate average.
The lone way is using array with variable size.
<3
EDIT (ANSWER THIS):
Let me tell full of story.
First Question of my teacher is:
Get entries (int) from user until user entered '-1', then type entry numbers from last to first. ( Teacher asked me to solve this project with recursive functions and with NO any array )
Second Question is:
Get n entries (float) from user and calculate their average. ( For this I must use arrays and functions or simple codes with NO any pointer )
Modern C has variable size arrays, as follows:
void example(int size)
{
int myArray[size];
//...
}
The size shouldn't be too large because the aray is allocated on the stack. If it is too large, the stack will overflow. Also, this aray only exists in the function (here: funtion example) and you cannot return it to a caller.
I think your task is to come up with a solution that does not use arrays.
For task 2 that is pretty simple. Just accumulate the input and divide by the number of inputs before printing. Like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float result = 0;
float f;
int n = 0;
printf("How many numbers?\n");
if (scanf("%d", &n) != 1) exit(1);
for (int i=0; i < n; ++i)
{
if (scanf("%f", &f) != 1) exit(1);
result += f;
}
result /= n;
printf("average is %f\n", result);
return 0;
}
The first task is a bit more complicated but can be solved using recursion. Here is an algorithm in pseudo code.
void foo(int n) // where n is the number of inputs remaining
{
if (n == 0) return; // no input remaining so just return
int input = getInput; // get next user input
foo(n - 1); // call recursive
print input; // print the input received above
}
and call it like
foo(5); // To get 5 inputs and print them in reverse order
I'll leave for OP to turn this pseudo code into real code.
You can actually use variable sized arrays. They are allowed when compiling with -std=c99
Otherwise, you can over-allocate the array with an arbitrary size (like an upper bound of your actual size) then use it the actual n provided by the user.
I don't know if this helps you, if not please provide more info and possibly what you have already achieved.
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 have a function called fun(int num, int * array); which takes an int and int array as its arugments. I'm trying to convert int to the array.
When i run the program i don't get the array displayed properly
int fun(int num, int*array) {
int count =0;
while(num>0) {
num/= 10;
count++;
}
array[count];
// for loop works
}
When i print the array in the program i.e. everytime I run the program i get random digits.
What this line is supposed to do ?
array[count];
Since your integer array will change in your fun function, you have to allocate the memory (by using malloc, realloc, ...).
edit : plus, you already change the value hold by "num" when you count how many digit there are in "num".
Make a copy of "num" !
edit 2 : the more i look your function, the more it seem you will have problem using it.
Fisrt, you want to explode your integer into an array of int.
Okay, but integer have range, thus meaning integer have a maximum digit.
From my memories, there are 20 digit in an 64bit integer.
So you can simply use "int array[NB_DIGIT_INT_MAX];" with "#define NB_DIGIT_INT_MAX 21".
So, allocating is not necessary AND add complexity in your code (the caller will have to free after the function call).
Second, your fun function doesn't say how many case will hold your integer.
Let's say num = 12, your array will have "array[0] = 1, array[1] = 2", but how do you know where to stop ?
If num = 2345, how do you know that only the 4 first case in your array is legit ?
There are 2 way : You have an another variable that hold the actual size of the array, or you have a special value in your array that say "it's the end" (like '\0' for char array used as string).
You can use "-1".
Let's give a try, and don't hesitate to ask question if thing are unclear (english is not my motherlanguage)
Your array is not even allocated, this can not work as expected. You are even lucky not to have a segmentation fault. If you want to add an integer to an array making it grow, you need to allocate a larger array, copy the values and add the new one to the new array and delete the previous array, keeping array variable as a pointer to the new array. Moreover, you need to pass the size of the actual array as an argument of fun.
The count variable can be global, Initialize it outside all functions like this
short count;
The whole program could be modified like below
#include<stdio.h>
#include<stdlib.h>
short count;
void fun(int num, int **ptr) {
// You need a pointer to a pointer and return type can be void
int num_copy=num;
count=0; // Setting the count to zero
while(num_copy>0) {
num_copy/= 10; // Don't modify the original number
count++;
}
//Allocate enough memory to store the digits
*ptr=malloc(count*sizeof **ptr);
if(NULL==*ptr){
perror("Can't allocate memory");
exit(1);
}
// Then do the loop part with original num
for(int i=count -1; i>=0; i--) {
(*ptr)[i] = num%10;
num /= 10;
}
// By now you have an array 'array' of integers which you could print in main.
}
int main()
{
int number = 123456789;
int *array;
fun(number,&array); // &array is of type pointer to a pointer to integers
//Now print the individual digits
printf("Individual digits are : \n");
for(int i=count-1;i>=0;i--)
printf("%d\n",array[i]);
}
Looks to me like you are converting from an integer to digits. But I don't see where your code writes anything to the array.
If the array wasn't initialized before this, that would explain why it still contains random values.
I'm quite puzzled by why my variable NumberOfArrays changes the second time through the for loop in my code. Can anyone help me out?
#include <stdio.h>
#include <cs50.h>
int main(int argc, string argv[])
{
//variable declarations
int NumberOfArrays = 0;
int arrayRack[0];
//Get number of arrays
printf("Key in the number of arrays you'd like to have\n");
NumberOfArrays = GetInt();
//Get number for each element in arrayRack[]
for(int i = 0; i < NumberOfArrays; i++)
{
printf("give me an int for the %i th array\n", i + 1);
arrayRack[i] = GetInt();
// *** on the second pass, my "NumberOfArrays" gets adjusted to my GetInt number here. Why?
}
//print out numbers stored in respective arrays
for(int j = 0; j < NumberOfArrays; j++)
{
printf("{%i}<-- number in %ith array\n", arrayRack[j], j + 1);
}
return 0;
}
Because you declared arrayRack as an empty array ([0]). Try int arrayRack[100]; or some other number, and make sure that NumberOfArrays is less than that number before you use it.
Explanation: (edit note that this may vary by compiler) your variables are most likely stored on the stack in nearby memory addresses. So arrayRack points somewhere close to NumberOfArrays in memory. C doesn't generally check if you've run off the end of an array, so accessing arrayRack[1] doesn't cause a compiler error in this situation. However, arrayRack[1] isn't part of your array, so accessing it actually accesses something else — in this situation, NumberOfArrays.
Edit gcc permits length-0 arrays but does not allocate space for them per this. However, length-0 arrays are prohibited by the C standard (e.g., see this, the answers to this, and this). Given the behaviour you've seen, it looks to me like the compiler is allocating one int's worth of space on the stack, pointing arrayRack to that space, and packing that space right next to NumberOfArrays. As a result, &(arrayRack[1]) == &NumberOfArrays. In any event, using variable-length arrays as suggested by #dasblinkenlight is a cleaner way to handle this situation.
In general, given int arrayRack[N];, you can only safely access arrayRack[0] through arrayRack[N-1].
You declared the array too early. Move the declaration to after the call of GetInt(), like this:
printf("Key in the number of arrays you'd like to have\n");
int NumberOfArrays = GetInt();
int arrayRack[NumberOfArrays];
Note: NumberOfArrays is not an ideal name for the variable, because it denotes the number of array elements, not the number of arrays; your code has only one array.
I have been attempting to wrap my head around an idea that I am certain is possible, I just am not sure if I am going about it in the right way. My intention is to create an array and then fill it with as many values as the user wants. However my goal is to not use any defined value per se. I would like to be able to continue increasing it the amount of values it can contain indefinitely.
This is the test code I have been using to try and figure this out:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i;
int Up;
int Ary[0];
printf("Please enter the number of integers you want to input: ");
scanf("%d", &Up);
for(i = 0; i < Up; i++)
{
printf("Please enter a number: ");
Ary[i] = (int) malloc(sizeof(int));
scanf("%d", &Ary[i]);
}
for(i = 0; i < Up; i++)
{
printf("%d ", Ary[i]);
if(i % 10 == 0)
{
printf("\n");
}
}
return 0;
}
This may be a poor way of attempting to figure this out and I may also be doing this is a completely wrong way; However I get a segmentation fault sometimes. If I use small values such as only entering 4 or 5 values it works fine, however if I enter 10 values it gives me a segmentation fault. If I enter 50 values, it lets me enter all 50 but gives me a segmentation fault after printing out the 41st value.
The code itself is simply a means to an end. Ultimately what I would like to know is how I can set up an array of anything that can have values added to it indefinitely while retaining previous values using dynamic memory allocation?
PS. I hope this defines my question well enough, however if it does not I would like to refine my question so it is more clear. Please make a comment if this is unclear and why.
This isn't going to work:
int Ary[0];
You've made an array with no elements; the only valid use of such an array is to take its address, but you can't index into it as you have done.
Instead, you should make a pointer to what will later be allocated as an array:
int *Ary;
Then when you know how many integers you want:
Ary = malloc(Up * sizeof(int));
Now you can do Ary[index] for any index from 0 to (Up-1). If you later want to enlarge the array, you can use realloc() (many tutorials online for that).
You need to use dynamic allocation, what you are doing right now is static allocation, you need to learn how to use malloc and free.
So keep in mind that what you want to do is not "efficient" but can definitely be done as a learning exercise to learn how to make such a container.
What you need to do is allocate the amount of memory needed to contain the amount of values currently in your array +1 more value every time you want to "add" a new value to your array, for example: malloc(sizeof(int)*(<current_number_of_values>+1)).
I say "add" in quotes because what you will have to do is actually allocate memory for a brand new array every time and copy over your old values plus the new value the user enters and then free your old array to avoid memory leaks.
There are STL containers that do this internally but much more efficiently but I assume you are doing this to learn and not use your own containers for anything serious.