显示一系列双打

时间:2015-02-24 22:44:42

标签: c arrays

我想编写一个函数将n个双精度数组转换为字符串,show函数,如:

struct vec {   uint64_t n;   double *x;  };

char *show(struct vec *v) {...}

请注意,我不想打印它们,只是对字符串进行序列化。

我怎样才能在C中做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以这样做:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAX_DOUBLE_LENGTH 15

typedef struct
{
  size_t n;
  double* x;
} DoubleArray;


int ShowArray(const DoubleArray* const doubleArrayPtr, char** const resultStringPtr)
{
  int errorCode = 0;

  char* tempStr = NULL;

  char str[MAX_DOUBLE_LENGTH + 2]; /* 1 for trailing space and 1 for null-terminator */

  size_t N = 0;
  size_t i = 0;

  if (doubleArrayPtr == NULL || resultStringPtr == NULL)
  {
    errorCode = 1;
  }
  else
  {
    if (doubleArrayPtr->n != 0)
    {
      /*
        calculating max string length from:

        str = <double01> <space> <double02> <space> <double03> <null-terminator>
        ex.: str = '3.25 4.75 0.01 5.678\0'
      */
      N = doubleArrayPtr->n * MAX_DOUBLE_LENGTH + doubleArrayPtr->n;

      tempStr = malloc(N * sizeof(*tempStr));

      if (tempStr == NULL)
      {
        errorCode = 1;
      }
      else
      {
        memset(tempStr, 0, N * sizeof(*tempStr));

        for(i = 0; i < doubleArrayPtr->n; i++)
        {
          sprintf(str, "%.6f ", doubleArrayPtr->x[i]);
          strcat(tempStr, str);
        }
        tempStr[strlen(tempStr) - 1] = '\0';

        /* string formed -- allocating buffer for result */
        (*resultStringPtr) = malloc((strlen(tempStr) + 1) * sizeof(**resultStringPtr));
        if ((*resultStringPtr) == NULL)
        {
          errorCode = 1;
        }
        else
        {
          /* exporting result */
          memcpy((*resultStringPtr), tempStr, strlen(tempStr) * sizeof(*tempStr));
          (*resultStringPtr)[strlen(tempStr)] = '\0';
        }
      }
      free(tempStr);
      tempStr = NULL;
    }
  }

  return errorCode;
}

int main(void)
{
  /* test code part */
  DoubleArray d;

  char* s = NULL;

  size_t i = 0;

  srand(time(NULL));

  d.n = rand() % 21;

  d.x = malloc(d.n * sizeof(*d.x));

  for(i = 0; i < d.n; i++)
  {
    d.x[i] = (rand() % 99999) / 100.0;
    printf("[%d] = %f\n", i, d.x[i]);
  }

  ShowArray(&d, &s);
  printf("str = '%s'\n", s);

  free(d.x);
  free(s);
  return 0;
}