[英]What will be the output of printf(“%s”,*&*str); where in str is a pointer?
[英]Showing where the pointer is in the output
我是C語言的新手,在語法和指針方面遇到了一些問題。
我有一個數組
int ar[6] = {2, 3, 6, 7, 1, 9};
我有一個指針
int* p = ar;
在輸出中,而不是打印出指針所指向的數字,我想在該數字的下面有一個^。 我希望它隨着指針的移動而移動。
我想要這樣的輸出:
The array = {2 3 6 7 1 9}
^
但我不知道如何跳過“數組= {”部分
我只是像這樣打印數組
printf("The array = { ");
for(int i=0; i< 6;i++){
printf("%d ", ar[i]);
}
我使用getchar()移動指針,因此來自用戶的輸入。
p = &a[0];
c = getchar();
if(c =='a'){
if(p == &ar[0]){
p--;
}
if( c=='d'){
p++;
}
我不知道是否有更簡便的方法可以做到這一點。
你可以試試這個-
#include <stdio.h>
#include <string.h>
int main(){
int ar[6] = {2, 3, 6, 7, 1, 9};
int* p = ar+2;
const char *s="int ar[6] = {"; // starting part of string
printf("%s",s); // print string
for(int i=0; i< 6;i++){
printf("%d ", ar[i]); // print array elements
}
printf("}\n"); // get to next line
size_t n=strlen(s); // calculate length of declaration part
for(int i=0;i<n;i++)
printf(" "); // print number of spaces
for(int i=0; i< 6;i++){
if(p==ar+i){
printf("^"); // if true print ^
break;
}
else
printf(" "); // if not then print 2 spaces
}
}
優化打印數字的部分。
// Use variables to help match the output
char const* prefix1 = "The array = { ";
char const* prefix2 = " ";
// Print the numbers first.
printf("%s", prefix1);
for(int i=0; i< 6;i++){
printf("%d ", ar[i]);
}
printf("\n");
這是打印^
符號的代碼。 您可以針對a
元素的地址測試指針值,並打印^
符號。 當數字不僅限於一位時,這將起作用。
// Print the the ^ symbol at the right place
printf("%s", prefix2);
for(int i=0; i< 6;i++) {
if ( p == &ar[i] ) {
printf("^");
break;
}
// Print the number to the temporary buffer.
// If the length of the buffer is 6, we need to print 6 spaces.
char temp[20];
sprintf(temp, "%d ", a[i]);
int len = strlen(temp);
for ( int j = 0; j < len; ++j )
{
temp[j] = ' ';
}
printf("%s", temp);
}
printf("\n");
以評論中提到的@Barmar為基礎,這就是我要做的。
int main() {
const char text[] = "The array = { ";
int print_offset[6];
int ar[6] = {2, 3, 6, 7, 1, 9};
char c;
int i;
print_offset[0] = printf("%s", text) + 1;
for(i=0; i<5;i++){
print_offset[i+1] = print_offset[i] + printf("%d ", ar[i]);
}
printf("%d }\n", ar[i]);
i = 0;
while(1) {
c = getchar();
if(c =='a'){
i++;
i %= 6;
printf("%*c\r", print_offset[i], '^');
}
else if(c=='d'){
i--;
if(i < 0)
i = 5;
printf("%*c\r", print_offset[i], '^');
}
}
}
由於printf的返回值,我在print_offset
存儲了必須打印^
的偏移量。 然后,在我的printf中使用*
寬度說明符在先前計算的偏移量處打印'^'。
這樣做的好處是,即使您要打印2個或更多字符的int
,此代碼也可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.