c - 指向字符串的指针数组,发生段错误

标签 c pointers gcc libc

我正在学习c中的指针 我写了一个小程序,但是我遇到了段错误 我不知道问题出在哪里 请让我知道代码的问题,它是一个指向字符串的指针数组, 这是一个指向结构体的指针。

# include <stdio.h>
#include <stdlib.h>
 # include <string.h>
char   *sum(char **sol) ;
 char  *summer_sum(char*** solcs) ;
int main()
{
char* datum ="teststring";
sum(&datum);
}


char *sum(char** sol)  
{
printf("\n   value is : %s",*sol);
summer_sum(&sol);
return "1" ; 
}

char *summer_sum(char***  solcs)  
{
int i=0;
typedef struct
{
char *asg[40];
}nlist;
nlist *n1;
for( i=0 ; i<= 38 ;i++)
{ 
n1->asg[i] = calloc(1,1*sizeof(*solcs));
strcpy(n1->asg[i],**solcs);
printf("\n %d value is : %s",i,n1->asg[i]);
} 

return NULL; 
}

最佳答案

n1 在未初始化的情况下使用:

n1->asg[i] = calloc(1,1*sizeof(*solcs));

另一方面,如果要分配足够的空间供strcpy使用,则必须使用strlen而不是sizeof

并且您不需要双指针或三指针,您的代码得到简化:

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

void sum(char *sol);
char *summer_sum(char *solcs);

int main(void)
{
    char *datum = "teststring";
    sum(datum);
}

void sum(char *sol)  
{
    printf("\n   value is : %s", sol);
    summer_sum(sol);
}

char *summer_sum(char *solcs)  
{
    int i = 0;
    size_t len;
    typedef struct {
        char *asg[40];
    } nlist;

    nlist *n1 = malloc(sizeof(*n1));
    if (n1 == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    len = strlen(solcs); /* No need to compute len on each iteration */
    for (i = 0; i <= 38; i++) { /* you are filling 39 and declared 40 */
        n1->asg[i] = calloc(1, len);
        /* Always check the result of (m/c/re)alloc */
        if (n1->asg[i] == NULL) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        strcpy(n1->asg[i], solcs);
        printf("\n %d value is : %s", i, n1->asg[i]);
        /* Don't forget to free */
        free(n1->asg[i]);
    }
    free(n1);
    return NULL; 
}

关于c - 指向字符串的指针数组,发生段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20882314/

相关文章:

c - 如何从C中的函数返回2个暗淡字符数组

java - 如何使用 JNI 将终端输出从 C 程序重定向到 System.out?

c - 使用函数创建链接列表时出现问题

c++ - 有没有一种在转换后使用 views::filter 的有效方法? (范围适配器)

macos - 使用 Homebrew 安装 OpenCV 时遇到问题

java - 使用 Antlr 获取标识符和函数名

将 char 数组中的十六进制地址转换为 uint8_t

c - 将结构传递给函数 C

c - 插入二叉树时出现错误?

c++ - Caffe 安装问题,远程服务器,ld 找不到 -<package>