令人震惊的事实:数组和指针并不相同
4.1 数组并非指针
/* x is pointer point to type int */
extern int *x;
/* y is an array of type int, the length is not certain. It's storage by definited in somewhere. */
extern int y[];
/*
** header.h
*/
#ifndef HEADER_H
#define HEADER_H
void print_info( void );
#endif
/*
** header_2.c.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "header.h"
int i = 2;
const char *x = "1234";
int y[] = {1, 2, 3};
size_t number = sizeof(y) / sizeof(*y);
void print_info( void ){
printf( "x = %s, strlen( x ) = %zd, sizeof(x) = %zd\n", x, strlen( x ), sizeof(x) );
size_t i;
for( i = 0; i < number; i++ ){
printf( "y[%d] = %d\n", i, y[i] );
}
printf( "\n" );
printf( "number = %zd, sizeof(y) = %zd\n", number, sizeof(y) );
}
/*
** main_2.c.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern const char *x;
extern int y[];
extern size_t number;
int main( void ){
printf( "x = %s, strlen( x ) = %zd, sizeof(x) = %zd\n", x, strlen( x ), sizeof(x) );
size_t i;
/*
** number = sizeof(y) / sizeof(*y);
** can't pass compilation:
** error: invalid application of 'sizeof' to incomplete type 'int[]'
*/
for( i = 0; i < number; i++ ){
printf( "y[%d] = %d\n", i, y[i] );
}
printf( "\n" );
/*
** printf( "number = %zd, sizeof(y) = %zd\n", number, sizeof(y) );
** number = sizeof(y) / sizeof(*y);
** can't pass compilation:
** error: invalid application of 'sizeof' to incomplete type 'int[]'
*/
return EXIT_SUCCESS;
}
输出:
/*
** main_2_2.c.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern const char *x;
extern int y[2];
extern size_t number;
int main( void ){
printf( "x = %s, strlen( x ) = %zd, sizeof(x) = %zd\n", x, strlen( x ), sizeof(x) );
size_t i;
number = sizeof(y) / sizeof(*y);
for( i = 0; i < number; i++ ){
printf( "y[%d] = %d\n", i, y[i] );
}
printf( "\n" );
printf( "number = %zd, sizeof(y) = %zd\n", number, sizeof(y) );
return EXIT_SUCCESS;
}
输出: