簡體   English   中英

如何在C中返回指向字符串數組的指針

[英]How to return pointer to an array of strings in C

函數如何返回指向字符串數組的指針?

我必須不使用C的string.h庫來執行此操作。 這是我到目前為止的內容:

#include <stdio.h>
#include <stdlib.h>

char* myFunc(){
    char* result[2];

    // the strings are originally dynamically allocated with some
    // function parameters which i've omitted to simplifiy the question.

    result[0] = "abc";
    result[1] = "def";
    return result;   
}

int main(void){
    char* result = myFunc();
    printf("%s\n%s\n", result[0], result[1]);
    return 0;
}

我希望有兩個字符串,但是編譯器將返回以下內容:

error: return from incompatible pointer type [-Wincompatible-pointer-types]
     return result;

您的類型不匹配。

您的函數定義為返回char *但返回的是char *[] ,它會衰減為char ** 這就是警告的意思。

將返回類型更改為char ** ,並將返回值分配給該值。 同樣,您不能返回指向局部變量的指針,因此您需要像在代碼注釋中所說的那樣動態分配數組。

#include <stdio.h>
#include <stdlib.h>

char **myFunc(){
    char **result = malloc(2 * sizeof(*result));

    result[0] = "abc";
    result[1] = "def";
    return result;   
}

int main(void){
    char **result = myFunc();
    printf("%s\n%s\n", result[0], result[1]);
    return 0;
}
char** result = myFunc();

但是函數中的yout變量是自動的,並且在函數范圍之外不存在

char** myFunc(){
    char** result = malloc(2 * sizeof(*result));
    result[0] = something;
    result[1] = something_else;
    return result;   
}

暫無
暫無

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

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