How could I read let's say 10 floats and store them in an array without wasting any memory?
int size = 10;
float vet[size];
for(i = 0; i < size; i++){
scanf("%f", &vet[i]);
}
As simple as it could be :)
Aha. It's not reading the floats that's the problem, it's the memory. You read in i, and you need an array that holds exactly i floats.
This really does smell like homework, which is fine, but I'm too much the teacher to give you the full answer. So I'll tell you, what you need is a C function named malloc() and a C operator (it looks like a function but it's actually built into the language) named sizeof.
Have a look at this tutorial.
Yup, you got it there. Here's the code from your comment, formatted.
int n,index;
float temp;
scanf("%d",&n);
float *pValues=(float *)calloc(n,sizeof(float));
for(index=0;index<n;index++) {
scanf("%f",&temp);
*(pValues+index)=temp;
}
I'd do it with two changes:
Its more idiomatic to use malloc for anything besides characters
In C, arrays and pointers have a very close relationship; in fact *(pValues+index) is exactly equivalent to pValues[index].
So I'd rewrite this as:
int n,index;
float temp;
scanf("%d",&n);
float *pValues=(float *)malloc(n*sizeof(float));
for(index=0;index<n;index++) {
scanf("%f",&temp);
pValues[index]=temp;
}
Let's look at one more transformation of the code. You have pValues, which is a pointer to float. You have &temp, which is also a pointer to float, because & is the address-of operator and temp is a float. AND, you're just doing pointer arithmetic with your index. So, we could rewrite this one more time as:
int n,index; // Don't need temp
scanf("%d",&n);
float *pValues=(float *)malloc(n*sizeof(float));
for(index=0;index<n;index++) {
scanf("%f",pValues+index);
}
Now, quiz question: what would happen if you made the loop
for(index=0;index<n;index++) {
scanf("%f",pValues++);
}
You'll have to be more specific about the problem.
Unless you have something else that you need to do with these numbers, then the easiest way to save memory is not to store them in an array to begin with.
It sounds like what you want is something like.
sum = 0;
do
read current
sum += current
while (you haven't yet read 10 numbers);
The answer to your question is that you cannot add things to an array and expect the array to use any memory.
float arr[10];
for(i = 0; i < 10; i++){
scanf("%f", &arr[i]);
}
I know, it's like the above, but doesn't use the extra int in case it's not optimized out. hehe
To use even less memory us the code below. They're all read into an array, but only the last one to be read in is in the array:
float arr[1];
for(i = 0; i < 10; i++){
scanf("%f", &arr[0]);
}
sounds like homework.
read the number of floats from the input.
multiply that by the size of an individual float
allocate that exact number of bytes storing the address in a pointer to floats
have a loop read in the floats from the input
have a loop that adds up all the floats in the array
My guess here is the homework lesson is to realize the connection between the term pointer and array, although you can do this without any array indexing, but your question implies that you have to use an array.
Related
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.
int n;
scanf("%d",&n);
int *score;
score=(int *)malloc(sizeof(int)*n);
int i;
for (i=0;i<n;i++)
{
scanf("%d",sizeof(int)*i+score);
}
printf("ok");
In the above code I get an error but when I comment the last line printf the program runs correctly.
what is the problem??
(I want to give n number from user without using arrays)
Pointer arithmetic of the form score + i is already done in multiples of sizeof(*score). So when you write score + i * sizeof(int) you doubly multiply by the size of the items. You reach way beyond the bounds of the buffer.
Either write it simply as score + i, or if you insist on doing the multiplication yourself, be sure to cast to a character pointer type first:
(int*)((char*)score + i * sizeof(int))
Oh, and don't cast the result of malloc. C doesn't require it, and it's somewhat unidiomatic.
scanf("%d",sizeof(int)*i+score);
pointer arithmetic uses the pointer type, so here you are moving to sizeof(int)isizeof(int) bytes after score, instead just use scores+i.
My cousin has a school project and we can't figure out why is the array different the second time it's printed when there is no values changing in between?
Basically you enter a number which states how many rows/columns will the matrix have, and during first loop he assigns a number to every position and prints out the random number. However, the second time we go through the matrix the numbers are different and it seems that they are copied through the matrix from bottom left corner to top right corner for some reason. It seems strange to us because we never assign a different value to a position in the array after defining it for the first time.
int i,j,n,matrica[i][j],suma=0;
srand(time(NULL));
printf("\nunesi prirodan broj N[3,20] = \n");
scanf("%d",&n);
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
matrica[i][j]=rand()%100;
printf("%d, %d = %4d ",i, j, matrica[i][j]);
if(j==n-1) {
printf("\n");
}
}
}
printf("\n");
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf("%d, %d = %4d ", i, j, matrica[i][j]);
if(j==n-1) {
printf("\n");
}
}
}
And here is the result of this (the code I pasted here has 2 prints, and in the image there is 3 but every time you go through the matrix after the first time it's going to be the same):
We need to use malloc to allocate the dynamic amount of memory.
After
scanf("%d",&n) // PS You should check the return value - read the manual page
Put
matrica = malloc(sizeof(int) * n * n);
And declare it as
int *matrica;
Then replace
matrica[i][j]
with
matrica[i * n + j]
And after you have finished with matrica - use free i.e.
free(matrica);
int i,j,n,matrica[i][j]
At this point I must ask, what value do you think i and j will have? Right there you're invoking undefined behaviour by referring to variables declared with automatic storage duration which you've not initialised. Anything after this point is... undefined behaviour.
Having said that, I noticed a few other parts that look strange. Which book are you reading? The reason I ask is that the people I know to be reading reputable textbooks don't have these problems, thus your textbook (or resource, whatever) mustn't be working for you...
I can't read the commentary inside of the string literals, which is a shame, since that's usually quite valuable contextual information to have in a question. Nonetheless, moving on, if this were me, I'd probably declare a pointer to an array n of int, after asking for n, like so:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t n;
printf("Enter n, please: ");
fflush(stdout);
if (scanf("%zu", &n) != 1 || n == 0 || SIZE_MAX / n < n) {
puts("Invalid input or arithmetic overflow...");
return -1;
}
int (*array)[n] = malloc(n * sizeof *array);
if (!array) {
puts("Allocation error...");
return -1;
}
/* now you can use array[0..(n-1)][0..(n-1)] as you might expect */
free(array);
}
This should work for quite high numbers, much higher than int array[n][n]; would in its place... and it gives you that option to tell the user it was an "Allocation error...", rather than just SIGSEGV, SIGILL, SIGBUS or something...
... but nothing would be more optimal than just saving the seed you use to generate the random numbers, and the user input; that's only two integers, no need for dynamic allocation. There's no point storing what rand generates, amd you realise this, right? rand can generate that output purely using register storage, the fastest memory commonly available in our processors. You won't beat it with arrays, not meaningfully, and not... just not.
I have made a dynamic array of integers in C, here is my code
#include <stdio.h>
int main(){
int count=0, i, input;
int *myarr;
myarr=(int*)malloc(4*sizeof(int));
while(1){
scanf("%d", &input);
myarr[count]=input;
count++;
if (input == -1) break;
}
for (i=0; i<count; i++){
printf("%d ", myarr[i]);
}
return 0;
}
From the code, I thought i clearly made an array of 4 integers only i.e myarr[0] up to myarr[3], how come when i insert even 10 integers, it still prints all of them, it doesn't print garbage as i thought it would after the fourth integer... Maybe i didn't understand the point of dynamic creating an array?? Make me straight please!
You should only access myarr[0] up to and including myarr[3].
Accessing any other index is undefined behaviour: it might work, it might not.
Also, myarr[count]==input looks like a typo. Did you mean myarr[count] = input? The way you have it is testing if myarr[count] equals input. Technically the way you have it is undefined behaviour for any element of myarr since you are making use of uninitialised data.
My teacher gave an assignment to me. The question is below:=
Write a program that prompts the user to enter 10 double numbers. The program should accomplish the follwing:
a. Store the information in a 10-element array.
b. Display the 10 numbers back to the user.
I could do all of the above in main().
Hint: You should use loops, not hardcode the values 0 through 9. It should be easy to convert your program to accept 1000 numbers instead of 10.
For a bonus mark, do at least one of the tasks (a or b) in a separate function. Pass the array to the function; do NOT use global (extern) variables.
I confused above. I wrote a program in the source code. Am I doing wrong? It is below:=
#include<stdio.h>
int main(void)
{
int number[10];
int i;
for (i = 0; i <10; i++)
printf("%d.\n", i, number[i]);
printf("\n\nPress [Enter] to exit program.\n");
fflush(stdin);
getchar();
return 0;
}
Thanks.
Not too bad so far, I'd like to make the following comments:
if you need to input double numbers, you should probably use double rather than int.
you need a statement (maybe in your current loop but possibly in another loop preceding the current one) which inputs the numbers. Look into scanf for this.
Using %d with printf is for integers, not doubles. You will have hopefully already figured out the format string to used when you looked into scanf above.
Bravo for using the correct int main(void) form and for not including conio.h :-)
Once you've figured those bits out, then you can worry about doing it in a separate function.
Based on the code you have given above, I would suggest reading up on the following:
scanf
functions in C, particularly passing arrays to functions: this link should be good.
Note to OP: If you were able to do (a) and (b) in main(), the code above is not complete. It would be nice the functions you created for getting (a) and (b) above done for getting to the root of your "confusion".
Let me know in case you need more help.
HTH,
Sriram
Try this it may sloves your problem.
#include<stdio.h>
int main(void)
{
double number[10];
int i;
printf("Enter double numbers:");
for (i = 0; i <10; i++)
scanf("%lf",&number[i] );
printf("The numbers you entered are:");
for (i = 0; i <10; i++)
printf("%lf\n",number[i] );
return 0;
}