0
Follow
0
View

Pointer variable print string problem

a58438331 注册会员
2023-02-25 19:06

printf("str=%x,*str=%c", str, str); str=%c is just the first element of the output string. The correct output is printf("str=%s\n", str);

dingliwei888ddd 注册会员
2023-02-25 19:06

This answer partially references GPT and GPT_Pro to solve the problem better.
You can print a string using a pointer variable. The principle is to put the string in memory and then point the pointer to the memory address. Finally, by traversing the memory address to which the pointer points, we can output the string information to which the pointer points.

The specific steps are as follows:
  1. First define a character array in memory to store the string information to be output.
    char str[10] = "Hello";  // 定义一个字符数组,用来存储要输出的字符串
    
  2. then defines a pointer variable and points that variable to the character array defined above.
    char *p = str;  // 定义一个指针变量,并把该变量指向上述定义的字符数组
    
  3. Finally traverses the memory address to which the pointer variable points, and prints the string information to which the pointer points.
    while(*p != '\0')  // 遍历该指针变量指向的内存地址,直到遇到'\0'为止
    { 
     printf("%c", *p);  // 输出当前内存地址中的字符 
     p++;  // 指针变量 + 1
    } 
    
    That's how you print a string from a pointer variable, but the key is to use pointer variables to iterate over what you want to print. Of course, we can also use other methods, such as for loops, while loops, etc.
    If the answer is helpful, please accept it.

About the Author

Question Info

Publish Time
2023-02-25 19:06
Update Time
2023-02-25 19:06