Original: Address/pointer and string
When doing your homework today, I found one of the following problems.
The home page is this self-compiled strncpy function:
#include "ctype.h" #include "stdlib.h" #include "string.h" #include "windows.h" int main () {char *strata (char S1[],char s2[ ],int n); char nam1[41]= "Das"; char nam2[41]= "wo shi yi ge da sha bi"; Strata (nam1,nam2,4);p UTS (NAM1); System ("pause"); return 0;} Char *strata (char s1[],char s2[],int n) {int I;char *prt=s1;if (n>strlen (S2)) return "-1"; else{s2[n]= '; for (i=0;i <n;i++) s1[i]=s2[i];}}
Forget it all: The address of the array is passed in the argument.
Slowly found Char *prt=s1;
The array name itself is the pointer constant;
A string can assign a value to an address problem:
For statement char *a= "Hello";
For this declaration, the misconception is that a character pointer is declared (it points to a location) and the string is assigned to the address pointed to by the pointer expression "*a". But the positive solution is: After a character pointer is declared, it is assigned to the pointer variable A with the address of the first character of the string constant. That is, the correct order is: 1. Allocate memory to a character pointer; 2. Allocate memory to a string; 3. Assign the first address of the string to a character pointer; Here are two points to consider:①*a just points to a character. Examples are as follows:
[C + +]View Plaincopyprint?
- #include <stdio.h>
- #include <stdlib.h>
- int main (void) {
- char *a="BCD";
- printf ("Output character:%c/n", *a); /* Output character, using "%c" */<br> printf ("Output character:%c/n", * (a+1)); / * Output characters, using "%c" * /
- printf ("Output string:%s/n", a); / * Output string, use "%s", and a cannot have an asterisk "*" * /
- System ("pause"); / * In order to see the output results * /
- }
- /* Run the results as follows:
- Output character:b<br> output character: C
- Output string: bcd*/
② If a string constant appears in an expression, the value represented is the address of the first character of the string constant. So "Hello" just stands for its address.
- Char *a;
- a="Hello"; /* Here the string "Hello" represents only the address of its first character * /
There are no string variables in C, so character arrays are generally used when storing string constantsto store.
The array is a contiguous storage space, where two important quantities are recorded: the first address and the space size.
and the pointer does not care about its length, as long as the record ere address is OK.
Char *a;//request space Address
a= "Hello";//a points to ' H ', and memory is open.
for ease of understanding, some places can be "equivalent" to the address/pointer and the string, the address/pointer to the variable is the first character of the string.
If you have a better understanding, I hope you will review
Address/pointer and string