c - 为什么会导致 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]
解决方案
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;
}
推荐阅读
- java - 如何使用 Spring Security 配置不同的路径?
- c# - 如何从动作委托访问参数并在异常情况下传递给另一个方法?
- pandas - Pandas,将所有数据框转换为唯一的分类值
- react-native - 标头在本机反应中不可见
- arrays - Mongodb嵌套数组匹配
- scala - 如何从 http 响应中保存标头
- bash - 我目前在两台机器上运行 cron 脚本来执行任务 - 我可以将它们组合成一个使用两台服务器的脚本吗?
- c++ - 如何在派生构造函数中初始化从基类继承的向量
- excel - 使用 While 循环获取特定列中的行句柄
- c# - 为什么这个 Base36 随机字符串不使用 RandomNumberGenerator 随机分布字符