Article Directory
foreword
This article mainly introduces the written test questions related to C language pointers and arrays.
1. Array-related written test questions
(1) Integer array
Let's look at the first group of questions first:
#include <stdio.h>
int main()
{
int a[] = {
1,2,3,4 };
printf("%d\n", sizeof(a));
printf("%d\n", sizeof(a + 0));
printf("%d\n", sizeof(*a));
printf("%d\n", sizeof(a + 1));
printf("%d\n", sizeof(a[1]));
return 0;
}
sizeof(): Find the length of the array (it returns the number of bytes of memory occupied by an object or type)
The diagram is as follows:
Topic 2:
#include <stdio.h>
int main()
{
int a[] = {
1,2,3,4 };
printf("%p\n", &a);
printf("%p\n", &a + 1);
printf("%p\n", &a[0]);
printf("%p\n", &a[0] + 1);
return 0;
}
The diagram is as follows:
(2) Character array
Let's first understand the difference between sizeof and strlen .
sizeof: It is a unary operator in C language, and its operands can be data types, functions, variables, etc. For example, calculate the storage space of int type data: sizeof(int)
strlen: Calculate the length of a string. Provided by the standard library of the C language.
Note : When strlen calculates the length of the string, the '\0' character is used as the end mark.
Consider this example:
#include <stdio.h>
#include<string.h>
int main()
{
char a1[] = {
'h','e','l','l','o' };
char a2[] = "hello";
printf("%d\n", sizeof(a1));
printf("%d\n", sizeof(a2));
printf("%d\n", strlen(a1));
printf("%d\n", strlen(a2));
return 0;
}
The diagram is as follows:
topic:
#include <stdio.h>
#include<string.h>
int main()
{
char arr[] = {
'h','e','l','l','o' };
printf("%d\n", sizeof(arr));
printf("%d\n", sizeof(*arr));
printf("%d\n", sizeof(arr[1]));
printf("%d\n", sizeof(&arr));
printf("%d\n", sizeof(&arr + 1));
printf("%d\n", sizeof(&arr[0] + 1));
return 0;
}
The result is as follows:
Two, the pointer
(1) Topic 1:
#include <stdio.h>
int main()
{
int a[5] = {
1, 2, 3, 4, 5 };
int *ptr = (int *)(&a + 1);
printf( "%d,%d", *(a + 1), *(ptr - 1));
return 0;
}
Result analysis:
(2) Topic 2:
int main()
{
int a[4] = {
1, 2, 3, 4 };
int *ptr1 = (int *)(&a + 1);
int *ptr2 = (int *)((int)a + 1);
printf( "%x,%x", ptr1[-1], *ptr2); //%x以16进制打印
return 0;
}
Result analysis:
Summarize
That's all for this article.