I'm new to C, coming from Java.
I made the following trivial program that compiles fine, but nano throws me a Segmentation Fault whenever I run it. The point of it is to traverse through the array and have it print out each element on a separate line.
int main()
{
int array[5] = {1, 2, 3, 4, 5};
int i = 0;
for (i = 0; i < sizeof(array); i++)
{
puts(array[i]);
}
}
What am I doing wrong?
sizeofgives the size of the object, in bytes. That is not the same as the number of elements in an array (unless the size of an element is 1 byte). To get the number of elements, you must divide the value by the size of a single array element. Also, you can't pass aninttoputs, which expects a string, i.e. achar *.gcc -std=c11 -pedantic-errors.