关于c语言字符串中sizeof指针的问题

#include<stdio.h>
#include<time.h>
#include<assert.h>
int main()
{
  FILE *f1=fopen("C:/Users/yangb/Desktop/11.txt","r");
  assert(f1);
  char ch[100];
  fgets(ch,100,f1);
  printf("%s\n",ch);
  printf("%s\n",ch+1);
  char* p=ch;
  printf("%d\n", sizeof(ch));
  printf("%d\n", sizeof(p));
  printf("%d\n", sizeof(ch+1));

  printf("%d\n",strlen(ch));
  printf("%d\n",strlen(ch+1));

return 0;

}

运行后其结果为:

1 2 3 4 5

 2 3 4 5

100
4
4
10
9

Process returned 0 (0x0)   execution time : 0.200 s
Press any key to continue.

只有定义字符数组的头指针里面含有这个数组字符信息,比如数组长度,其他的都特定指数组中的一个元素。

printf(“%s”, p)是把指针p指向的内容以及他后面指向的内容截止到' \0'全部打印出来。

fgets(ch, 100, f1)是把f1的一行最多99个字符放入字符数组ch中,其中第100个字符是'\0'。

如果这里把 字符数组改为字符指针:

#include<stdio.h>
#include<time.h>
#include<assert.h>
int main()
{
  FILE *f1=fopen("C:/Users/yangb/Desktop/11.txt","r");
  assert(f1);
  char* ch=(char*)malloc(100*sizeof(char));
  fgets(ch,100,f1);
  printf("%s\n",ch);
  printf("%s\n",ch+1);
  char* p=ch;
  printf("%d\n", sizeof(ch));
  printf("%d\n", sizeof(p));
  printf("%d\n", sizeof(ch+1));

  printf("%d\n",strlen(ch));
  printf("%d\n",strlen(ch+1));

return 0;
}

运行后其结果变为了:

1 2 3 4 5

 2 3 4 5

4
4
4
10
9

Process returned 0 (0x0)   execution time : 0.194 s
Press any key to continue.


由此可见 想知道一个串的大小,如果用sizeof的话只能是字符数组的首地址ch,虽然p指向ch,但p不包含ch中的信息,sizeof(p)是一个字符的大小,并非这个数组的

我们可以用strlen来确定字符串的长度(10是包含了空格和换行符的,文件中有换行)



猜你喜欢

转载自blog.csdn.net/yangbomoto/article/details/78425046