首页 > 解决方案 > 为什么会导致 SIGSEGV(信号 11)(核心转储)?

问题描述

这里我有一个函数,它从 struct 中获取一个字符串数组并返回 struct integer_array。

#include "string.h"
#include "stdlib.h"
integer_array* my_count_on_it(string_array *p1)
{
    integer_array *pusher;
    int size = p1->size;
    char** str = p1->array;
    pusher = (integer_array*) malloc(size*sizeof(integer_array));

    for (int i = 0;i<size;i++)
    {
        pusher->array[i] = strlen(str[i]);
    }
    return pusher;
}

函数原型(c):

  typedef struct s_string_array {
    int size;
    char** array;
  } string_array;

 typedef struct s_integer_array {
   int size;
   int* array;
 } integer_array;

@param {string_array*} param_1
@return {integer_array*}


integer_array* my_count_on_it(string_array* param_1) {

}


这就是它应该如何工作

输入/返回示例:

输入: ["This", "is", "the", "way"]
返回值: [4, 2, 3, 3]

输入: ["aBc"]
返回值: [3]


标签: carraysfunctionruntime-errorstructure

解决方案


integer_array *pusher初始化良好。但是其中的各个指针也应该被初始化。您可能想要这样做pusher->array = (int*) malloc(sizeof(int) *size)。但老实说,我没有掌握你想通过该函数调用实现什么。您声明了一个数组,integer_array但您似乎只使用了第一个元素,我怀疑它们是您代码中的潜在逻辑错误。

编辑:正如@David C. Rankin 提到的,也可能是您没有为p1->array

您可能希望拥有这样的功能。

#include "string.h"
#include "stdlib.h"
#include "stdio.h"

typedef struct s_string_array {
    int size;
    char** array;
} string_array;

typedef struct s_integer_array {
    int size;
    int* array;
} integer_array;

integer_array* my_count_on_it(string_array *p1)
{

    integer_array* pusher = (integer_array*) malloc(sizeof(integer_array));

    pusher->size = p1->size;
    pusher->array = (int*) malloc(sizeof(int) * p1->size);

    for (int i = 0; i < p1->size; i++)
    {
        pusher->array[i] = strlen(p1->array[i]);
    }
    return pusher;
}

int main()
{
    string_array *p1 = NULL;

    /* collect data from user */

        // Setup p1{} struct

    integer_array* pusher = my_count_on_it(p1);

    for (int i = 0; i < pusher->size ; i++)
        printf(" %d ", pusher->array[i]);

    return 0;
}

推荐阅读