2015-02-07 44 views
0

我目前正在尝试在c中创建一个程序,它将返回一个指向2个字符串数组的指针。第一个是字符串s在奇数位置的字符,第二个是在偶数位置的字符。我在C中没有经验,所以我需要一些关于这个程序的帮助。我一直在尝试使用python和java知道的代码进行编码,但它似乎没有遵循与指针相同的原则。这里是我的代码:一个c程序,它返回一个指向2个字符串数组的指针

#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的每个索引。

有关如何解决此问题的任何想法?谢谢。

回答

2

此行不会做任何好:

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

malloc返回一个指向新分配的内存。在上面的行中,dest[][]中的方括号需要无符号整数。指针可以被转换为整数,但这不是你想要的。它可能会编译,但它可能不会运行,当然不会做你想要的。

另外,sizeof(s)将指针的大小返回到s,而不是字符串的长度。 C中的字符串实际上只是以NULL结尾的数组char s,而数组通过指针传递给函数,而不是它们的全部内容。要获取字符串的长度,请改为使用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终止符。

在C中的malloc a multi-dimensional array很棘手。另一方面,一维数组很容易。只是把destodddesteven像他们的阵列,即使他们真的指针:

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

的代码在你for循环看起来并不像它会工作。看起来您可能一直试图使用+=来连接字符串,但它只会添加数字。我无法很快弄清楚你应该在for循环中设置什么,所以'a''b'只是占位符。

1

您有几个问题。正如你的编译器应该告诉你的,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; 
} 
相关问题