我在学习sizeof,这让我很沮丧.我决定这样做.
#include<stdio.h>
#include<string.h>
int main(){
char *myWord="PIZZA";
printf ("The size of P is...:%d\n",sizeof("P"));
printf ("The size of I is...:%d\n",sizeof("I"));
printf ("The size of Z is...:%d\n",sizeof("Z"));
printf ("The size of A is...:%d\n",sizeof("A"));
printf ("The size of R is...:%d\n",sizeof("R"));
printf ("The size of PIZZA is...:%d\n",sizeof("PIZZA"));
printf ("The size of *PIZZA is..:%d\n",sizeof(myWord));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我很惊讶地看到结果:
The size of P is...:2
The size of I is...:2
The size of Z is...:2
The size of A is...:2
The size of R is...:2 …Run Code Online (Sandbox Code Playgroud) 请考虑以下代码
#include <stdio.h>
void print(char string[]){
printf("%s:%d\n",string,sizeof(string));
}
int main(){
char string[] = "Hello World";
print(string);
}
Run Code Online (Sandbox Code Playgroud)
而输出是
Hello World:4
Run Code Online (Sandbox Code Playgroud)
那有什么不对呢?
#include "usefunc.h" //don't worry about this -> lib I wrote
int main()
{
int i;
string given[4000], longest = "a"; //declared new typdef. equivalent to 2D char array
given[0] = "a";
printf("Please enter words separated by RETs...\n");
for (i = 1; i < 4000 && !StringEqual(given[i-1], "end"); i++)
{
given[i] = GetLine();
/*
if (sizeof(given[i]) > sizeof(longest))
{
longest = given[i];
}
*/
printf("%lu\n", sizeof(given[i])); //this ALWAYS RETURNS EIGHT!!!
}
printf("%s", longest);
}
Run Code Online (Sandbox Code Playgroud)
它为什么总是返回8 ???