How do I know in a C loop if my iterating variable i reached the end of an array pointed…
- User
How do I know in a C loop if my iterating variable i reached the end of an array pointed to by a pointer? for (int i = 0; i < count; i++) { if (array[i] // is part of array ) { /* code */ }
}
Assistant
In C, when working with pointers and arrays, there are several ways to check if you've reached the end:
- If you know the size beforehand:
int* array = /* ... */; int size = /* known size */; for (int i = 0; i < size; i++) { // Safe to access array[i] }- If the array is null-terminated (like strings):
int* array = /* ... */; for (int i = 0; array[i] != '\0'; i++) { // Process until null terminator }- If you're using pointer arithmetic:
int* array = /* ... */; int* end = array + size; for (int* ptr = array; ptr < end; ptr++) { // Use *ptr }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.