簡體   English   中英

指向字符數組的第一個字符?

[英]Pointer to the first character of a character array?

編輯:顯然,我必須在pigLatin方法的開頭先聲明char *,然后在該方法的后面將其初始化為&word [counter]。 有人知道這是為什么嗎? 我正在使用Visual Studio 2010。

我很難弄清楚為什么這會給我一個編譯時錯誤。 有問題的代碼:

#include <stdio.h>
#include <string.h>
#include <conio.h>

char *pigLatin(char *word)
{
   if (word[0] == 'a' || word[0] == 'e' || word[0] == 'i'
           || word[0] == 'o' || word[0] == 'u')
   {
       char yay[] = "yay";
       strcat(word, yay);
       return word;
   }
   else
   {
       int length = strlen(word);
       int counter = 0;
       char addOn[] = "";
       char remainder[] = "";
       char yay[] = "yay";
       printf("%s", yay);

       char *first = &word[counter]; 
       printf("%c", *first); // error is here, don't know why it doesn't print
       return word;
   }
}


int main()
{
   char hello[] = "hello";
   pigLatin(hello);
   printf("%s", hello);
   getch();
   return (0);
}

1> ------開始構建:項目:Program_One,配置:Win32版本------

1> programone.c

1> programone.c(12):警告C4996:'strcat':該函數或變量可能不安全。 考慮改用strcat_s。 要禁用棄用,請使用_CRT_SECURE_NO_WARNINGS。 詳細信息請參見在線幫助。

1> programone.c(24):錯誤C2143:語法錯誤:缺少';' 在“類型”之前

1> programone.c(25):錯誤C2065:“ first”:未聲明的標識符

1> programone.c(25):錯誤C2100:非法重定向

==========構建:0成功,1失敗,0最新,跳過0 ==========

我看不到為什么我指向數組“ hello”的第一個字符的指針無法正確打印。

提前致謝 !

您沒有分配指針變量指向第一個字符的地址。 您正在將字符本身的值分配給指針變量,這就是編譯器錯誤的原因。

您需要更改此行:

char *first = word[counter]; 

對此:

char *first = &word[counter]; 

或者,改為執行以下操作:

char *pigLatin(char *word)   
{   
    int counter = 0;   
    printf("%c", word[counter]);
    return word;   
}   

更新:即使代碼可以編譯,也很危險。 有關strcat()的編譯器警告有效。 如果輸入的單詞以元音開頭,則您沒有分配足夠的內存來將"yay"附加到輸入單詞上。 為了真正使此代碼更安全,您應該使用std::string類而不是原始指針:

#include <conio.h> 
#include <string> 

std::string pigLatin(const std::string &word) 
{ 
    switch( word[0] )
    {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u': 
            return word + "yay"; 
    }

    int length = word.length(); 
    int counter = 0; 
    //...

    printf("%c", word[counter]);
    return word; 
} 

int main() 
{ 
   std::string word = pigLatin("hello");
   printf("%s", hello.c_str()); 
   getch(); 
   return 0; 
} 

這行在這里:

char *first = word[counter]; 

應該是這個:

char *first = &word[counter];

由於您指向的是指針所指向的值,而不是內存地址本身,因此,要獲取實際值,需要在對數組的調用之前使用“&”號。

您正在告訴編譯器指向first ,它的值word[counter] ,這意味着它在內存中的指着某處奇怪。 您要指向數組的第一個元素,因此需要替換:

char *first = word[counter];

與:

char *first = &word[counter];

要么:

char *first = word;

編輯 -您在注釋中提到的編譯器錯誤與源代碼的第23和24行有關。 您上面發布的示例中少於23行。 因此,錯誤必須是您未在此處發布的一些額外代碼中...

Edit2-經過一些小的調整,您的代碼對我來說看起來很有效: http : //codepad.org/73BKMSgv

char str [] =“ test”;
字符* p;
p = str;
printf(p [0]);

輸出:
Ť

暫無
暫無

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

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