簡體   English   中英

ac程序,該程序返回指向2個字符串的數組的指針

[英]a c program which returns a pointer to array of 2 strings

我目前正在嘗試在c中創建一個程序,該程序將返回一個指向2個字符串的數組的指針。 第一個是位於奇數位置的字符串s的字符,第二個是位於偶數位置的字符串的字符。 我沒有C方面的經驗,因此在此程序方面需要一些幫助。 我一直在嘗試使用我從python和java中獲得的知識進行編碼,但是它似乎並沒有遵循與指針相同的原理。 這是我的代碼:

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

char **parity_strings(const char *s){

char dest[malloc((char)sizeof(s)/2 + 1)][malloc((char)sizeof(s)/2 + 1)]; //trying to allocate memory to an array of size 2 which will hold 2 strings.

int i;
for(i = 0; i < sizeof(s); i+= 2){    //iterating through odd strings
    s[0] += dest[i];
}
for(i= 2; i< sizeof(s); i += 2){    //iterating through even strings (I suppose i could have just appended using 1 for loop but oh well
    s[1] += dest[i];
}

return dest;


}

int main(int argc, char **argv) {
char **r = parity_strings(argv[1]);
printf("%s %s %s\n", r[0], r[1], argv[1]);
return 0;
} 

內存分配也很痛苦...我不知道它是否正在按照我打算的那樣做。 我正在嘗試將字節的大小(以字節+ 1個字節為單位)分配給數組Dest的每個索引。

有想法該怎么解決這個嗎? 謝謝。

這行不會有什么好處:

char dest[malloc((char)sizeof(s)/2 + 1)][malloc((char)sizeof(s)/2 + 1)];

malloc返回一個指向新分配的內存的指針。 在上面的行中, dest[][]的方括號需要無符號整數。 指針可以強制轉換為整數,但這根本不是您想要的。 它可能會編譯,但可能不會運行,並且肯定不會執行您想要的操作。

同樣, sizeof(s)返回指向s的指針的大小,而不是字符串的長度。 C中的字符串實際上只是char的以null終止的數組,並且數組使用指針而不是全部內容傳遞給函數。 要獲取字符串的長度,請改用strlen(s)

您可以執行以下操作:

char *destodd = malloc((strlen(s)/2 + 2));
char *desteven = malloc((strlen(s)/2 + 2));
char **dest = malloc(sizeof(char *) * 2);
dest[0] = desteven;
dest[1] = destodd;

我將您的+ 1更改為+2 長度為3的字符串在destodd需要3個字符:一個用於字符1,一個用於字符3,以及一個用於NUL終止符。

是相當棘手的malloc一個多維陣列中C.一維陣列,在另一方面,是容易的。 即使將destodddesteven當作數組來對待,即使它們確實是指針:

for (i = 0; i < strlen(s); i += 2){
    desteven[i] = 'a'; // Fix this
    destodd[i] = 'b';
}

for循環中的代碼似乎不起作用。 看起來您可能一直在嘗試使用+=來連接字符串,但是它只會添加數字。 我無法快速弄清楚您應該在for循環中設置什么,因此'a''b'只是占位符。

你有幾個問題。 正如您的編譯器應該告訴您的那樣, char dest[malloc()]需要一個無符號指針的轉換,這是合法的,但不是您想要的。 更重要的是,如果取消引用指針,則返回指向分配給堆棧的數組的指針會導致未定義的行為,因為編譯器可能已經釋放了內存。 我不確定該函數的預期輸出是什么,但是就填充兩個字符數組而言,我認為最簡單的方法是:

char **parity_strings(char* buf) //Please avoid single letter variable names for anything but loop control
{
    size_t buflen = strlen(buf);
    if (NULL == char** dest = malloc(2 * sizeof(*dest)))
        ;//handle memory allocation error
    if (NULL == dest[0] = malloc(buflen * sizeof(*buf)))
        ;//handle memory allocation error
    if (NULL == dest[1] = malloc(buflen * sizeof(*buf)))
        ;//handle memory allocation error
    //Note that you would do the above two lines in a loop for a variable sized multidimensional array
    strncpy(dest[0], buf, 500);
    strncpy(dest[1], buf, 500); //If you need strings larger than 500 change as necessary, mostly only needed if you are taking input from someone else but it's good practice to use strncpy over strcpy)
    return dest;
}

暫無
暫無

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

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