1

.I have a big array of coordinates that looks like this

triangle_t teapot_model[] = {
{
.x1=5,
.y1=10,
},
{
.x1=20,
.y1=30,
},
(keeps going)

How can I print all of the items in this array without knowing their position? I want this output:

Output:
.x1=5 y1=10
.x1=20 .y1=30
5
  • 1
    It is not "sizeless". sizeof(teapot_model)/sizeof(teapot_model[0]) will tell you the exact number of elements (or you can count them manually). Commented Oct 10, 2019 at 19:55
  • the elements inside the array dont have a specific value. It wouldn't work to say print teapot_model[1] | how can i do that with the array i posted? Commented Oct 10, 2019 at 19:57
  • Do you know how to loop over an array? Commented Oct 10, 2019 at 19:58
  • It does not make any sense to say the elements inside the array do not have a specific value. Your example shows they have values. And, if they did not have values, what do you think you would be printing? (Technically, as defined by the C standard, it is possible for an object not to have a determinate value, but that is not what we are dealing with here.) Commented Oct 10, 2019 at 20:04
  • Is your array defined in the same routine in which you want to print the values? If not, how does the routine receive the array? Commented Oct 10, 2019 at 20:05

1 Answer 1

4

Array in C always has a size although implicit in your case.

To simply print each element of your array, using the below code should suffice

int sizearray = sizeof teapot_model  / sizeof *teapot_model;

for (int i = 0; i < sizearray; i++) 
{
    printf(".x1=%d .y1=%d\n", teapot_model[i].x1, teapot_model[i].y1);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Tip: Do not use sizeof(teapot_model) / sizeof(triangle_t). If the type of teapot_model is ever edited, the person changing it might miss places like this, and then you would have an error because the size of the array is divided by something different from the size of an element. Use sizeof teapot_model / sizeof *teapot_model. (And parentheses are needed when using sizeof with expressions rather than types. It is an operator, not a function.)
edited, usually I play with void *, so I mostly work with sizeof(type)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.