簡體   English   中英

如何取消引用字符串指針

[英]How to dereference a string pointer

我在從代碼中獲取所需行為時遇到問題。 我是 C 語言的新手(盡管我通常使用 C++ 編程,所以我有點熟悉),我不確定 go 的問題在哪里。 在下面的代碼中,當嘗試使用傳遞給 function 的“輸入”字符串的內容填充 2 個字符串時,結果是 memory 位置被傳遞給 2 個字符串,這意味着當我對單個字符串執行修改時,原始數據已編輯...我希望將初始數據復制到分配給新字符串的新 memory 位置。

bool interpretInput(char *input)
{
    char *name = malloc(MAX_NAME_SIZE / 2);
    char *surname = malloc(MAX_NAME_SIZE / 2);

    if (name == NULL | surname == NULL)
    {
        return 1;
    }

    int length = (int) strlen(input);
    if ((length > 0) && (input[length - 1] == '\n')) input[length - 1] = '\0';

    if (surname = strpbrk(input, " "))
    {
        int sLength = (int) strlen(surname);

        for (int i = 0; i < sLength; i++)
        {
            surname[i] = surname[i + 1];
        }

        length = (int) strlen(input);

        for (int i = 0; i <= length - sLength; i++)
        {
            name[i] = input[i];
        }

        length = (int) strlen(name);
        sLength = (int) strlen(surname);

        printf("Name: %s length: %d \n", name, length);
        printf("Surname: %s length: %d \n", surname, sLength);
    }
    else
    {
        printf("Name length: %d", length);
    }

    return 0;
}

編輯:實際上,我想用另一個數組的每個增量處的值填充一個數組,而不使用 strcpy。

我想你想要strcpy(char* dest, char* src) 取消引用 char* 只會為您生成字符串中的第一個字符。

#include <stdio.h>

int main()
{
    char* test = "hello world";
    char* test2 = malloc(11*sizeof(char));
    strcpy(test2, test);

    printf("%s\n", test);
    printf("%s\n", test2);
    test2[5] = '_';
    printf("%s\n", test);
    printf("%s\n", test2);
    printf("%c\n", *test);

    free(test2);
}

吐出來

hello world                                                                                                                                                                        
hello world                                                                                                                                                                        
hello world                                                                                                                                                                        
hello_world                                                                                                                                                                        
h

暫無
暫無

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

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