首页 > 解决方案 > 如何使用 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;
}

标签: c

解决方案


推荐阅读