【问题标题】:How to use dynamic allocation instead of static int?如何使用动态分配而不是静态int?
【发布时间】:2016-06-14 09:32:59
【问题描述】:
 int* asciiCode(char c1, char c2){
   static int asciiCode[126];
   /code/
   /code/
   return asciiCode;
 }

我可以在这种情况下使用分配而不是静态 int 吗?我不确切知道上述指针数组的元素数量?如果是,我该怎么做?

【问题讨论】:

  • May I can use allocation..什么分配?动态的?为什么?
  • 请说明您的具体问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。请参阅“如何提问”页面以获得澄清此问题的帮助。
  • 是的,动态分配,抱歉
  • 实际上想解决哪个问题?对我来说看起来像 XY Problem
  • 没有“指针数组”,基本看不懂代码应该做什么。

标签: c arrays pointers static allocation


【解决方案1】:

这是一个您可能会发现有用的示例。 array 被分配并在后续调用中使用,以模拟使用静态数组来保存调用之间的值。

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

int* asciiCode(char c1, char c2, int *asciiCodeArr, int size ){
   int static counter = 0;

   if(asciiCodeArr==NULL)
   {
     asciiCodeArr = (int *) malloc( sizeof(int)* size);
     if(!asciiCodeArr) return NULL;
   }

   printf("c1=%c ",c1);
   printf("c2=%c ",c2);

   asciiCodeArr[counter] = c1;
   counter = counter + 1;

   asciiCodeArr[counter] = c2;
   counter = counter + 1;

  return (asciiCodeArr);
 }

int main(void) {
    int i;
    int *array=NULL;
    int size = 128; // To Hold 128 - 7bits Standard ASCII characters 

    array = asciiCode('1', '2', array, size);
    if(!array){
        printf("allocation error!\n");
        return -1;
    }

    // array = 
    asciiCode('3', '4', array, size);

    printf("\narray content in hex: ");    
    for(i=0;i<4;i++)
    {
       printf("%X ", array[i]);
    }

   free(array);
   return 0;
}

输出:

c1=1 c2=2 c1=3 c2=4 
array content in hex: 31 32 33 34 

【讨论】:

    【解决方案2】:

    我可以在这种情况下使用分配而不是静态 int 吗?

    是的,只要一些例程还free()分配的内存。

    我不知道上面指针数组的元素个数是多少?

    您的代码中没有指针数组。如果您指的是int 数组,那么项目的数量似乎是 126。这看起来很奇怪,旧的 7 位 ASCII 有 128 个符号,而不是 126 个。

    如果是,我该怎么做?

    使用malloc 然后返回一个指针。

    【讨论】:

    • 我认为标准的 7 位 ASCII 有 128 个符号 ASCII
    • @sg7 嗯,是的,实际上 0 也可能是一个符号。我会编辑,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2019-03-20
    • 2020-12-05
    • 1970-01-01
    相关资源
    最近更新 更多