返回指向`char`的指针数组

时间:2016-12-27 09:39:10

标签: c arrays string pointers

这个程序应该连接字符串,但我不知道如何将字符串数组返回main。

char **conca(char *a[], int n)
{

char buff[200];

char **conc[n];
for (int i = 0; i < n; i++)
{
    strcpy(buff,a[i]);
    strcat(buff,"-");
    int l = strlen(buff);
    *conc[i] = malloc((l+1)*sizeof(char));
    strcpy(*conc[i],buff);
}

return *conc;

main.c

char **conca(char *a[], int n);

int main(int argc, char *argv[])
{
    if(argc == 1)
    {
        printf("Uso: %s <stringa> <stringa> ... <stringa> \n",argv[0]);
        return 1;
    }

    int dim = argc - 1;

    int pos = 0;
    char *array[dim];

    for(int i = 1; i <= dim; i++ )
    {
        array[pos] = malloc((strlen(argv[i])+1)*sizeof(char));
        strcpy(array[pos],argv[i]);
        pos++;
    }

    char **f = conca(array, dim);
}

程序触发分段错误(核心转储)。

如何在main中打印连接字符串?

4 个答案:

答案 0 :(得分:2)

您需要返回char而不是指向#include <stdio.h> #include <stdlib.h> #include <string.h> char *join(char *a[], int n, char sep){ size_t lens[n], total_length = 0; for (int i = 0; i < n; i++){ total_length += (lens[i] = strlen(a[i])); } total_length += n;//sep * (n-1) + NUL char *ret = malloc(total_length); char *wk = ret; for (int i = 0; i < n; i++){ if(i) *wk++ = sep; memcpy(wk, a[i], lens[i]); wk += lens[i]; } *wk = 0; return ret; } int main(int argc, char *argv[]){ if(argc == 1){ printf("Uso: %s <stringa> <stringa> ... <stringa> \n", argv[0]); return 1; } int dim = argc - 1; char *concata = join(argv+1, dim, '-'); puts(concata); free(concata); } 的指针数组 喜欢这个

String wind;

答案 1 :(得分:0)

段错误的原因是你不能像* conc [i]那样初始化内存:

*conc[i] = malloc((l+1)*sizeof(char))

而你必须做

conc[i] = malloc((l+1)*sizeof(char))

但你这里有另一个问题。您将数组声明为局部变量。 conc 是一个指针数组,存储在conca()的堆栈帧中,因此从技术上讲,这是未定义的行为。解决方案是将 conc 更改为char **并使用malloc()分配整个数组 (并记得稍后释放)

所以我修改了你的char ** conca(char * a [],int n)函数。所以我使用了** conc而不是指针数组。

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

char **conca(char *a[], int n)
{

char buff[200];

char **conc = (char **)malloc(n*sizeof(char *));
int i=0;
for (i = 0; i < n; i++)
{
    strcpy(buff,a[i]);
    strcat(buff,"-");

    int l = strlen(buff);
    conc[i]=(char *)malloc((l+1)*sizeof(char));
    strcpy(conc[i],buff);
}

return conc;
}

int main(int argc, char *argv[])
{
        if(argc == 1)
        {
                printf("Uso: %s <stringa> <stringa> ... <stringa> \n",argv[0]);
                return 1;
        }

        int dim = argc - 1;

        int pos = 0;
        char *array[dim];
        int i=0;
        for(i = 1; i <= dim; i++ )
        {
                array[pos] = malloc((strlen(argv[i])+1)*sizeof(char));
                strcpy(array[pos],argv[i]);
                pos++;
                pos++;
        }
        char **f = conca(array, dim);

        for(i=0;i<dim;i++)
        printf("%s",f[i]);

        printf("\n\n");
}

答案 2 :(得分:0)

您应该返回char **

,而不是返回char *

malloc也没有错误检查,这是必需的,因为如果不成功可以返回NULL指针。

以下示例显示了这一点:

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

char *join(char *argv[], int n);

int main(int argc, char *argv[]){
    char *result;

    if(argc == 1){
        printf("Uso: %s <stringa> <stringa> ... <stringa> \n", argv[0]);
        return 1;
    }

    result = join(argv, argc);
    printf("%s\n", result);

    free(result);
    result = NULL;

    return 0;
}

char *join(char *argv[], int n) {
    int i;
    const char *sep = "-";
    char *string;
    size_t strsize = 0;

    for (i = 1; i < n; i++) {
        strsize += strlen(argv[i])+1;
    }

    string = malloc(strsize);
    if (!string) {
        printf("Cannot allocate memory for string.\n");
        exit(EXIT_FAILURE);
    }

    *string = '\0';
    for (i = 1; i < n; i++) {
        strcat(string, argv[i]);
        if (i < n-1) {
            strcat(string, sep);
        }
    }
    return string;
}

输入:

$ gcc -Wall -Wextra -Wpedantic -std=c99 -o concat concat.c

$ ./concat Always check return of malloc

输出:

Always-check-return-of-malloc

答案 3 :(得分:0)

以下代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 正确地将错误消息输出到stderr
  4. 正确检查错误
  5. 包含正确的#include语句
  6. 被恰当评论
  7. 包含一些原始发布的代码,作为对进行更改的highlite的评论
  8. 避免不必要的变量
  9. 显示生成的连接字符串
  10. 自行清理
  11. 现在是代码

    #include <stdio.h>  // printf(), fprintf()
    #include <stdlib.h> // exit(), EXIT_FAILURE, malloc(), realloc(), free()
    #include <string.h> // strlen(), strcat()
    
    
    //char **conca(char *a[], int n);
    // function prototypes
    char *concat(char *argv[], int argc);
    
    int main(int argc, char *argv[])
    {
        if(argc == 1)
        {
            fprintf( stderr, "Uso: %s <stringa> <stringa> ... <stringa> \n",argv[0]);
            //printf("Uso: %s <stringa> <stringa> ... <stringa> \n",argv[0]);
            exit( EXIT_FAILURE );
            //return 1;
        }
    
        char *newCat = concat( argv, argc );
    
        printf( "%s\n", newCat );
        free( newCat );
    } // end function: main
    
    
    char *concat(char *argv[], int argc)
    {
    
        char *newString = malloc(1);
        if( !newString )
        { // then malloc failed
            perror( "malloc failed" );
            exit( EXIT_FAILURE );
        }
    
        // implied else, malloc successful
        newString[0] = '\0';
    
        for( int i = 1; i <= argc; i++ )
        //for(int i = 1; i <= dim; i++ )
        {
            char * tempptr = realloc( newString, strlen( newString) + strlen(argv[i])+2 );
            if( !tempptr )
            { // then realloc failed
                 perror( "realloc failed" );
                 free( newString );
                 exit( EXIT_FAILURE );
            }
    
            // implied else, realloc successful
    
            newString = tempptr;
            //array[pos] = malloc((strlen(argv[i])+1)*sizeof(char));
            //strcpy(array[pos],argv[i]);
            strcat( newString, argv[i] );
    
            // avoid a trailing '-' in final string
            if( i < (argc-1) )
            { 
                strcat( newString, "-" );
            }
        } // end for
    
        return newString;
    } // end function: concat