c - 如何使用 strtok
问题描述
以下是 codewars 培训的解决方案。 https://www.codewars.com/kata/59f4a0acbee84576800000af/train/c
Test Crashed
Caught unexpected signal: SIGSEGV (11). Invalid memory access.
我收到这样的错误消息,怎么了?我认为这可能是 strtok 函数的一部分,但请告诉我出了什么问题。
#include <stdlib.h>
#include <string.h>
double pos_average(char *s, unsigned n)
{
char **matrix;
char *p;
unsigned int i, j, k;
unsigned int subst_len = ( strchr(s,',') - s ) / sizeof(char);
double count = 0;
matrix = (char**)calloc( n + 1 ,sizeof(char*) );
if(!matrix) exit(0);
for(i = 0; i < n; i++)
{
matrix[i] = (char*)calloc( subst_len + 1 ,sizeof(char) );
if(!matrix[i]) exit(0);
}
for(i = 0; i < n; i++)
{
if(i == 0){
p = strtok(s, " ");
strncpy(matrix[i], p, subst_len);
}
else{
p = strtok(NULL," ");
strncpy(matrix[i], p, subst_len);
}
}
for(i = 0; i < n - 1; i++)
{
for(j = i + 1; j < n; j++)
{
for(k = 0; k < subst_len; k++)
{
if(matrix[i][k] == matrix[j][k]) count++;
}
}
}
for(i = 0; i < n; i++) free(matrix[i]);
free(matrix);
return (count / ( ( (double)n * ( (double)n - 1.0 ) ) / 2.0 ) ) * 100.0;
}
解决方案
推荐阅读
- javascript - 如何从显示画布或图像的外部网站(带有 url 参数)嵌入图片
- mysql - MySQL数据库表无法拖入visual studio数据集界面
- python - 使用 UptimeRobot 时如何更新 JSON 文件中的数据?
- algorithm - 算法中运行时间和执行时间的区别?
- javascript - 如何将注释样式应用于可能有重叠部分的文本片段?
- c++ - 如何修复从 QDataStream 读取的方法
- javascript - MERN Stack 应用程序在本地计算机上运行,但在 heroku 上失败
- php - 如何仅在 LastName 的回显行名称下划线?
- python - 无法在电子邮件中发送主题 - python
- python - 如何操作 python 列表中的数据来修改和存储?