#Arrays
42 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
my main problem is the arrays isn't getting printed
Am i supposed to print the 1 2 3 4 5 with a loop?
What are you trying to do by passing the 101st element of elements to scanf?
That’s
- out of bounds
- not a pointer
well i'm trying to store all the inputs as an array
You want the user to be able to input a variable amount of elements to an array?
The first int will indicate the amount of elements
1 2 3 4 5 as an example will make an array of 5 elements
then i want to print those elements
#include <stdio.h>
char printarray(char x);
int main()
{
int elements[100];
int x;
scanf("%d %d", &x, elements[100]);
printf("%d elements: %d\n", x, printarray(elements));
}
char printarray(char x)
{
for (int i = 0; i < x; ++i)
{
printf("%d", elements[i]);
}
}
Am i on the right track?
Your print function should return void since it’s not returning anything. The argument should also be an int, not a char
But you’re still reading your numbers wrong. I‘m not sure how to use scanf properly, but I think you need a for loop taking each element of the array one at a time
I had a better idea
#include <stdio.h>
int main()
{
int elements[100];
int x;
scanf("%d ", &x);
for(int i = 0; i < x; ++i)
{
scanf(" %d", elements[i]);
}
printf("%d elements: ", x);
for(int i = 0; i < x; ++i)
{
printf("%d ", elements[i]);
}
printf("\n");
}
I was thinking something like this
and within that for loop i print every element while incrementing i
That would print them if you took the input correctly, yes
Oh have i messed up the scanf?
.
OOoh i see what you mean
Something like this?
Is i in scope of the for loop only?
Can i use i on both of my for loops?
or do i need a different variable
You need to pass &elements[i] to scanf, since you need to pass a pointer to that element
That seems to have done the trick!
However i'm not sure why i need "&" tho
i was taught by my teacher for example when i utilize strings
or when i scan string i don't use &
That doesn't apply to arrays?
Strings are arrays of chars. The variable that you assign the string to is already a pointer to the first char in that array.
You need to pass a pointer to scanf so it can actually modify that variable‘s value. When you find an element of the array, then it will give you the actual value at that index. & returns a pointer to that value
Aaah that makes sense
It works perfectly just as intdned
@woven ploverthank you so much for your help!

Awesome
@pure coral Has your question been resolved? If so, type !solved :)
!solved