簡體   English   中英

將字符數組的指針發送到C中的函數

[英]Sending a pointer of a character array to a function in C

好吧,長話短說,我遇到了一些麻煩:我正在嘗試將字符數組(字符串)的起始地址發送給函數。 函數獲得指針后,我希望函數一一解析字符(以修改某些字符)。 截至目前,我只是將其設置為打印每個字符,但我仍然非常無法做到這一點。

這就是我所擁有的:

#include "system.h"
#include <stdio.h>

typedef unsigned int uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;

void EXCLAIM(char *msg){
    char the_char = 0;
    the_char = msg;
    while (the_char != 0)
    {
        printf(the_char);
        *msg = *(msg++);
        the_char = *msg;
    }
}

int main(void) {
    char *first_str = "This is a test. Will this work. I. am. Not. Sure...";
    while (1) {
        EXCLAIM(first_str);
    }
}

編輯:

這是我嘗試執行的更新代碼; 發送指針並檢查每個字符,並用感嘆號替換所有句點。

#include "system.h"
#include <stdio.h>

typedef unsigned int uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;

void exclaim(char *msg){
    int i;
    for( i=0; msg[i]; i++ )
    {
        if (msg[i] == '.') {
            msg[i] = '!';
        }
    }
printf(msg);
}

int main(void) {
    char *the_sentences = "This is a test. Will this work. I. am. Not. Sure...";
    while (1) {
        exclaim(the_sentences);
    }
}

謝謝大家的幫助!

嘗試這樣的事情:

#include <stdio.h>

void exclaim(char * s)
{
    while (*s != '\0')
    {
        putc(*s);
        ++s;
    }
}

筆記:

  • 別喊 除預處理器宏外,請勿將所有大寫形式都使用。

  • 打印字符,而不是字符串。

  • 無需再進行復制。 函數參數已經是可以直接使用的局部變量。

您的main()很好。

問題出在EXCLAIM內的指針算法。

我可以看到兩個有用的不同版本:

使用指針算術

while (*msg)
{
    printf("%c", *msg);
    msg++
}

使用索引

int i;
char the_char;
for( i=0; msg[i]; i++ )
{
    printf( "%c", msg[i] );
}

您應該使用:

  the_char = *msg;

不:

  the_char = msg;
*msg = *(msg++); 

您打算如何使用這一行代碼? 您了解它的實際作用嗎? 首先,您需要知道msg++更改指針的值。 然后,您將其分配給指向新位置的任何名稱分配。 這意味着整個字符串將被替換為字符串中第一個字符的副本。

故事的寓意是不要在一行代碼中做太多事情。 使用增量運算符++必須格外小心。 即使是經驗豐富的程序員也通常將msg++放在自己的行中,因為當您嘗試將其與復雜的表達式混合使用時,它會變得過於復雜。

未提及的某些事情,但是試圖修改字符串文字是未定義的行為。

您需要更改以下行,

char *the_sentences = "This is a test. Will this work. I. am. Not. Sure...";

到一個數組。

char the_sentences[] = "This is a test. Will this work. I. am. Not. Sure...";

然后隨意修改函數中的內容。

#include <stdio.h>

void foo(char *msg)
{
    for (; *msg; msg++)
        if (*msg == '?')
            *msg = '!';
}

int main(void)
{
    char line[] = "Hello, world?? How are you tonight??";

    foo(line);

    puts(line);
    return 0;
}

暫無
暫無

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

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