C integer/float array strange behavior -
okay fooling around making random programs , seeing outputs understanding how things work , noticed strange thing integer/float arrays. unlike char array '\0' character not stored directly after last entered element array. in integer array stored 2 elements after last element , in float 4 elements. here's code demonstrate strange fact. please me understand why happens.
#include <stdio.h> #include <string.h> void foo(int* x) { while ( *(x) != '\0' ) { printf("%i ",*x); ++x; } } void foo1(float* x) { while ( *(x) != '\0') { printf("%.1f ",*x); ++x; } } void foo2(char* x) { while( *(x) != '\0' ) { printf("%c",*x); ++x; } } int main(void) { int a[4] = {1,2,3,4}; float b[4] = {1.1,2.2,3.3,4.4}; char name[] = "muneeb"; foo(a); printf("\n\n"); foo1(b); printf("\n\n"); foo2(name); return 0; }
output:
1 2 3 4 -12345677723 -1623562626 1.1 2.2 3.3 4.4 0.0 0.0 0.0 0.0 -0.0 -1.3
in general, there no 0 element after end of array. cannot assume there is; kind of code segfault. finding 0 there coincidence.
in char
arrays in particular, rule same. however, literal string "hello, world!"
1 char
longer you’d counting characters. equivalent to unmodifiable char[13]
of {'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\0'}
. lot of library functions working char
s expect terminating '\0'
; no such expectation exists other types of arrays , need pass length explicitly.
also note *(x) != '\0'
treats '\0'
int
or float
zero, , equivalent *x != 0
or *x != 0.0f
(for different types of x
in different functions). if had stored actual 0 in 1 of arrays, have counted that.
since there no special sentinel convention int
or float
arrays (because 0
, 0.0f
reasonable values put in array), should create separate size_t
variable keep track of array’s length. then, if ever need create function acting on array, can give length
parameter , have iterate that. example:
void foo(int* x, size_t length) { (size_t = 0; < length; ++i) { printf("%i ", x[i]); } }
(i use size_t
here because typically represents size of structures in memory).
then can call foo(a, 4);
. if need variable-sized array, can create size_t a_length
variable when create a
, , update whenever a
’s size changes.
you might want char
arrays sometimes, such if have binary data might contain 0 bytes, or because scanning end of string takes time , don’t need @ each character.
Comments
Post a Comment