簡體   English   中英

您可以在指向數組的指針中打印內容嗎?

[英]Can you print contents in a pointer pointing to an array?

我正在講課的一張幻燈片中使用此代碼,我的問題之一是在打印數組時,為什么不能使用指針而不是僅打印“ a”,在打印語句的最后一行

printf("\n message after decryption: %s\n", a);    

我不明白為什么我們不能使用指針來打印數組。 有人可以向我解釋為什么不能這樣做嗎?

printf("\n message after decryption: %s\n", *q);  

#include <stdio.h>
#define NUM 78

int main()
{
   int i = 0;
   char a[] = "Hello CSE 240";
   printf("\n message: %s\n ", a);
   while(a[i] != '\0'){a[i] = *(a+i)+1;i++;}
   printf("\n message after encryption: %s\n ", a);
   char *q = a;
   while(*q != '\0'){*q = *q-1;q++;}
   printf("\n message after decryption: %s\n", a);
}

您想在q修改循環之后打印出數組的內容,但是在所有增量之后它都指向空終止字符,即'\\0' printf因此在printf使用q將僅打印此內容- message after decryption: -修改數組/字符串將不會打印。

用做q ,你需要重新分配q到數組的第一個元素: q=a while循環結束后。

然后此語句將按您希望的方式工作:

printf("\n message after decryption: %s\n", q);

最好使用適當的格式說明符更改打印語句。

 #include <stdio.h>
 #define NUM 78

 int main()
 {
     int i = 0;  
     char a[] = "Hello CSE 240";
     printf("\n message: %s\n ", a);

     while(a[i] != '\0'){a[i] = *(a+i)+1;i++;}
     printf("\n message after encryption: %s\n ", a);

     char *q = a;

     while(*q != '\0'){*q = *q-1;q++;
     //decrypting the value of a 
     }//end of this is pointing to null

     q=a;//repointing to point a     
     printf("\n message after decryption: %c\n", *q);//H is printed
     printf("\n message after decryption: %s\n", q);//Hello CSE 240 is printed 

 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM