簡體   English   中英

為什么會導致 SIGSEGV(信號 11)(核心轉儲)?

[英]Why it caused SIGSEGV (signal 11) (core dumped)?

在這里,我有 function 從結構中獲取字符串數組並返回結構整數數組。

#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;
}

Function 原型(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]


integer_array *pusher初始化良好。 但是其中的各個指針也應該被初始化。 您可能想要這樣做pusher->array = (int*) malloc(sizeof(int) *size) 但老實說,我沒有掌握你想通過 function 調用實現的目標。 您聲明了一個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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM