繁体   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