まず、ここにいくつかのコードがあります:
int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf("%u\n", sizeof(days));
printf("%u\n", sizeof(ptr));
return 0;
}
ptr
(32ビットシステムでは4バイトであるサイズを指定するのではなく)ポイントしている配列のサイズを確認する方法はありますか?
いいえ、できません。コンパイラーは、ポインターが何を指しているのかを知りません。既知の帯域外値で配列を終了し、その値までサイズをカウントするなどのトリックがありますが、それはを使用していませんsizeof()
。
もう1つのトリックは、Zanが言及したもので、サイズをどこかに隠しておくことです。たとえば、配列を動的に割り当てる場合は、必要なブロックより1 int大きいブロックを割り当て、最初のintにサイズをptr+1
格納して、配列へのポインタとして返します。サイズが必要な場合は、ポインタをデクリメントして、隠された値を確認します。配列だけでなく、ブロック全体を最初から解放することを忘れないでください。
答えはノーだ。"
C プログラマーが行うことは、配列のサイズをどこかに格納することです。malloc()
それは構造体の一部である可能性があります。または、配列の開始前に長さの値を格納するために、プログラマーが要求されたよりも少し多くのメモリを不正使用する可能性があります。
動的配列 ( mallocまたは C++ new ) の場合、他の人が述べたように配列のサイズを格納するか、追加、削除、カウントなどを処理する配列マネージャー構造を構築する必要があります。残念ながら、C はこれをほぼ同様に行いません。基本的に、格納する配列の種類ごとにビルドする必要があるため、管理する必要がある配列の種類が複数ある場合は面倒です。
例のような静的配列の場合、サイズを取得するために使用される一般的なマクロがありますが、パラメーターが実際に静的配列であるかどうかをチェックしないため、お勧めしません。ただし、マクロは実際のコードで使用されます。たとえば、Linux カーネル ヘッダーで使用されますが、以下のものとは若干異なる場合があります。
#if !defined(ARRAY_SIZE)
#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
#endif
int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf("%u\n", ARRAY_SIZE(days));
printf("%u\n", sizeof(ptr));
return 0;
}
このようなマクロに警戒する理由については、グーグルで検索できます。気をつけて。
可能であれば、より安全で使いやすい vector などの C++ stdlib を使用してください。
sizeof()を使用せずに、C++ テンプレートを使用したクリーンなソリューションがあります。次のgetSize()関数は、静的配列のサイズを返します。
#include <cstddef>
template<typename T, size_t SIZE>
size_t getSize(T (&)[SIZE]) {
return SIZE;
}
foo_t構造体の例を次に示します。
#include <cstddef>
template<typename T, size_t SIZE>
size_t getSize(T (&)[SIZE]) {
return SIZE;
}
struct foo_t {
int ball;
};
int main()
{
foo_t foos3[] = {{1},{2},{3}};
foo_t foos5[] = {{1},{2},{3},{4},{5}};
printf("%u\n", getSize(foos3));
printf("%u\n", getSize(foos5));
return 0;
}
出力:
3
5
この特定の例では、はい、typedef を使用する場合があります (以下を参照)。もちろん、このようにすれば、ポインターが何を指しているかを知っているので、SIZEOF_DAYS を使用しても問題ありません。
malloc() などによって返される (void *) ポインターがある場合、いいえ、ポインターが指しているデータ構造を判別する方法がないため、そのサイズを判別する方法がありません。
#include <stdio.h>
#define NUM_DAYS 5
typedef int days_t[ NUM_DAYS ];
#define SIZEOF_DAYS ( sizeof( days_t ) )
int main() {
days_t days;
days_t *ptr = &days;
printf( "SIZEOF_DAYS: %u\n", SIZEOF_DAYS );
printf( "sizeof(days): %u\n", sizeof(days) );
printf( "sizeof(*ptr): %u\n", sizeof(*ptr) );
printf( "sizeof(ptr): %u\n", sizeof(ptr) );
return 0;
}
出力:
SIZEOF_DAYS: 20
sizeof(days): 20
sizeof(*ptr): 20
sizeof(ptr): 4
魔法の解決策はありません。C は内省的な言語ではありません。オブジェクトは、それが何であるかを自動的に認識しません。
しかし、多くの選択肢があります:
この問題に対する私の解決策は、配列の長さを配列に関するメタ情報として struct Array に保存することです。
#include <stdio.h>
#include <stdlib.h>
struct Array
{
int length;
double *array;
};
typedef struct Array Array;
Array* NewArray(int length)
{
/* Allocate the memory for the struct Array */
Array *newArray = (Array*) malloc(sizeof(Array));
/* Insert only non-negative length's*/
newArray->length = (length > 0) ? length : 0;
newArray->array = (double*) malloc(length*sizeof(double));
return newArray;
}
void SetArray(Array *structure,int length,double* array)
{
structure->length = length;
structure->array = array;
}
void PrintArray(Array *structure)
{
if(structure->length > 0)
{
int i;
printf("length: %d\n", structure->length);
for (i = 0; i < structure->length; i++)
printf("%g\n", structure->array[i]);
}
else
printf("Empty Array. Length 0\n");
}
int main()
{
int i;
Array *negativeTest, *days = NewArray(5);
double moreDays[] = {1,2,3,4,5,6,7,8,9,10};
for (i = 0; i < days->length; i++)
days->array[i] = i+1;
PrintArray(days);
SetArray(days,10,moreDays);
PrintArray(days);
negativeTest = NewArray(-5);
PrintArray(negativeTest);
return 0;
}
しかし、私たちの友人が大々的に説明したように、この長さをチェックする方法がないため、格納する配列の正しい長さを設定することに注意する必要があります。
int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf("%u\n", sizeof(days));
printf("%u\n", sizeof(ptr));
return 0;
}
days[] のサイズは 20 で、要素数 * データ型のサイズです。ポインターのサイズは、それが何を指していても4です。ポインターは、そのアドレスを格納することによって他の要素を指すためです。
sizeof(ptr)
いいえ、配列ptr
が指しているサイズを見つけるために使用することはできません。
ただし、長さを余分なスペースに格納する場合は、余分なメモリ (配列のサイズよりも大きい) を割り当てると役立ちます。
文字列では'\0'
末尾に文字があるため、文字列の長さは のような関数を使用して取得できますstrlen
。たとえば、整数配列の問題は、終了値として値を使用できないことです。そのため、考えられる解決策の 1 つは、配列をアドレス指定し、NULL
ポインターを終了値として使用することです。
#include <stdio.h>
/* the following function will produce the warning:
* ‘sizeof’ on array function parameter ‘a’ will
* return size of ‘int *’ [-Wsizeof-array-argument]
*/
void foo( int a[] )
{
printf( "%lu\n", sizeof a );
}
/* so we have to implement something else one possible
* idea is to use the NULL pointer as a control value
* the same way '\0' is used in strings but this way
* the pointer passed to a function should address pointers
* so the actual implementation of an array type will
* be a pointer to pointer
*/
typedef char * type_t; /* line 18 */
typedef type_t ** array_t;
int main( void )
{
array_t initialize( int, ... );
/* initialize an array with four values "foo", "bar", "baz", "foobar"
* if one wants to use integers rather than strings than in the typedef
* declaration at line 18 the char * type should be changed with int
* and in the format used for printing the array values
* at line 45 and 51 "%s" should be changed with "%i"
*/
array_t array = initialize( 4, "foo", "bar", "baz", "foobar" );
int size( array_t );
/* print array size */
printf( "size %i:\n", size( array ));
void aprint( char *, array_t );
/* print array values */
aprint( "%s\n", array ); /* line 45 */
type_t getval( array_t, int );
/* print an indexed value */
int i = 2;
type_t val = getval( array, i );
printf( "%i: %s\n", i, val ); /* line 51 */
void delete( array_t );
/* free some space */
delete( array );
return 0;
}
/* the output of the program should be:
* size 4:
* foo
* bar
* baz
* foobar
* 2: baz
*/
#include <stdarg.h>
#include <stdlib.h>
array_t initialize( int n, ... )
{
/* here we store the array values */
type_t *v = (type_t *) malloc( sizeof( type_t ) * n );
va_list ap;
va_start( ap, n );
int j;
for ( j = 0; j < n; j++ )
v[j] = va_arg( ap, type_t );
va_end( ap );
/* the actual array will hold the addresses of those
* values plus a NULL pointer
*/
array_t a = (array_t) malloc( sizeof( type_t *) * ( n + 1 ));
a[n] = NULL;
for ( j = 0; j < n; j++ )
a[j] = v + j;
return a;
}
int size( array_t a )
{
int n = 0;
while ( *a++ != NULL )
n++;
return n;
}
void aprint( char *fmt, array_t a )
{
while ( *a != NULL )
printf( fmt, **a++ );
}
type_t getval( array_t a, int i )
{
return *a[i];
}
void delete( array_t a )
{
free( *a );
free( a );
}
#define array_size 10
struct {
int16 size;
int16 array[array_size];
int16 property1[(array_size/16)+1]
int16 property2[(array_size/16)+1]
} array1 = {array_size, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
#undef array_size
array_size はsize変数に渡されます:
#define array_size 30
struct {
int16 size;
int16 array[array_size];
int16 property1[(array_size/16)+1]
int16 property2[(array_size/16)+1]
} array2 = {array_size};
#undef array_size
使用法は次のとおりです。
void main() {
int16 size = array1.size;
for (int i=0; i!=size; i++) {
array1.array[i] *= 2;
}
}