C字符串内存分配,C字符串表

时间:2014-05-20 20:12:12

标签: c cstring dynamic-allocation

我想制作动态分配的c-string表,但我想我不太了解这个主题,你可以向我解释一下还是更正我的代码?

#include <stdio.h>

    int main()
    {
        int i;
    char** t;
        t=(char**)malloc(16*sizeof(char*));

    for(i<0;i<100;i++)
    {
        *t[i]=(char*)malloc(16*sizeof(char));
    }

    return 0;
    }

3 个答案:

答案 0 :(得分:0)

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

int main(int I__argC, char *I__argV[])
   {
   int rCode=0;
   int i;
   char **t=NULL;
   size_t arraySize;

   /* Parse command line args. */
   if(2 != I__argC)
      {
      rCode=EINVAL;
      printf("USAGE: %s {dynamic array size}\n", I__argV[0]);
      goto CLEANUP;
      }

   arraySize=strtoul(I__argV[1], NULL, 0);
   if(0 == arraySize)
      {
      rCode=EINVAL;
      fprintf(stderr, "Cannot allocate a dynamic array of size zero.\n");
      goto CLEANUP;
      }

   /* Allocate a dynamic array of string pointers. */
   errno=0;
   t = malloc(arraySize * sizeof(*t));
   if(NULL == t)
      {
      rCode = errno ? errno : ENOMEM;
      fprintf(stderr, "malloc() failed.\n");
      goto CLEANUP;
      }

   memset(t, 0, arraySize * sizeof(*t));
   /* Initialize each pointer with a dynamically allocated string. */
   for(i=0; i<arraySize; i++)
      {
      errno=0;
      t[i]=strdup("A string");
      if(NULL == t[i])
         {
         rCode= errno ? errno : ENOMEM;
         fprintf(stderr, "strdup() failed.\n");
         goto CLEANUP;
         }
      }

CLEANUP:

   /* Free the array of pointers, and all dynamically allocated strings. */
   if(t)
      {
      for(i=0; i<arraySize; i++)
         {
         if(t[i])
            free(t[i]);
         }
      free(t);
      }

   return(rCode);
   }

答案 1 :(得分:0)

您应该将变量用于您想要的一切。例如,为char *类型的16个元素分配一个内存,结果,你有一个包含16个元素的数组,但是你会从0到100?为什么?

#include <stdio.h>

int main()
{
    int n = 16;
    int m = 16;
    // Allocate a memory for n elements of type char*
    char** t = (char**)malloc(n * sizeof(char*));
    for(int i = 0; i < n; ++i)
    {
        // For each element in array t - initialize with another array.
        // Allocate m elements of type char
        t[i] = (char*)malloc(m * sizeof(char));

        // Initialize
        for(int j = 0; j < m; ++j)
            t[i][m] = 'a';
    }

    // Print
    for(int i = 0; i < n; ++i)
    {
        for(int j = 0; j < m; ++j)
            printf("%c ", t[i][m]);
        printf("\n");
    }


    // Free allocated memory!
    for(int i = 0; i < n; ++i)
        free(t[i]);
    free(t);
    return 0;
}

答案 2 :(得分:-1)

您的代码可以更正,以便它可以创建100X16字符表或100字符串16字符长度的表。

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

int main()
{
    int i;
    int noOfStrings = 100;
    int eachStringLenght = 16;
     char** t;
    t=(char**)malloc(noOfStrings*sizeof(char*));

    for(i=0;i<noOfStrings;i++)
    {
        t[i]=(char*)malloc(eachStringLenght*sizeof(char));
    }

    return 0;
}