2012-09-25 32 views
0

假設我有一個字符串「很高興認識你!」,並且我想打印時沒有第一個字母,而只是打印出「滿足你的冰!訪問C程序中的字符串

我試着做如下,然而,編譯和運行後程序會自行關閉。

#include <stdio.h> 

int main(void) 
{ 
char *s = "nice to meet you!"; 

printf("Original string: %s\n",*s); 

printf("Pointer plus one gives: %s\n", *(s+1)); 

return 0; 
} 

我的程序有什麼問題?

+3

你*真正理解*這是什麼一樣'* s'?如果沒有,請參考你的書 - 通常指針很早就被引入了...... – Nim

+0

如何在調試器中運行它? –

+1

你的程序沒有什麼問題,它完全符合你的要求。你知道你在告訴它做什麼嗎? – Mike

回答

6

您應該打印s而不是*s

的%s格式令牌預期的指針。 s是一個指向字符串的指針,而*s是字符串中第一個字符的值。 printf("%s", *s)將打印一個字符串,從字符串中第一個字符的字符代碼的地址開始。這個地址可能不會對你的進程有效,因此你得到了未處理的異常。

+0

感謝您的解釋。我不知道「%s」會需要字符串文字的地址。 –

+0

@dizhang很高興幫助。如果你對這個答案感到滿意,你能接受它嗎(點擊左邊的upvote計數下的勾號大綱)? – simonc

2

mmhm,您使用指向字符串的指針而不是指向字符串的指針(使用printf)。嘗試

printf ("aaa %s bbb\n", s); 

printf ("aaa %s bbb\n", s+1); 
+0

非常感謝。主席先生,你是對的。 –

1

我嘗試做如下,然而,該方案將自行編譯並運行後關閉。

通過終端運行你的程序。你用什麼來編譯和運行你的程序?

我的程序有什麼問題?

*(s + 1)是單個字符。

3

* s將導致char的指針解引用。因此請嘗試以下操作:

#include <stdio.h> 

int main() 
{ 
char *s="nice to meet you!"; 

printf("Original string: %s \n",s); 
printf("Original first char: %c\n", *s); 

printf("Pointer plus one gives: %s\n", (s+1)); 

return 0; 
} 

查看區別。

問候

0

試試這個,只需使用dowhatopwant功能與您的字符串:

void my_putchar(char c) 
{ 
    write(1, &c, 1); 
} 

void dowhatopwant(char *str) 
{ 
    int cnt = 1; 
    while (s[cnt]) 
    { 
    my_putchar(s[cnt]); 
    cnt++; 
    } 
} 
0

代碼是做什麼你告訴它做的事,我想也許你不明白是什麼你告訴它要做。

char *s = "nice to meet you!"; 

// s is a pointer to a character 
// s* is the character that "s" points to 

您有s指向字符'n'。 s發生指向NULL終止字符串文字中的第一個字符。

printf("Original character: %c\n",*s); //Note the %c, we're looking at a character 
output-> Original character: n 

printf("Original string: %s\n",s); //Note the %s, and we're feeding the printf a pointer now 
output-> Original string: nice to meet you! 

當談到偏移:

*s  = the character s is pointing at, 'n' 
*(s+1) = the next character s is pointing at, 'i' 

VS:

s  = the address of the string "nice to meet you" 
(s+1) = the address of the string "ice to meet you" 
+0

謝謝你的傑出答案。問候你。 –