c - 如何使用动态分配代替静态int?

标签 c arrays pointers static allocation

 int* asciiCode(char c1, char c2){
   static int asciiCode[126];
   /code/
   /code/
   return asciiCode;
 }

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

最佳答案

这是一个您可能会觉得有用的示例。 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 

关于c - 如何使用动态分配代替静态int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37808181/

相关文章:

没遇到过的C错误

c++ - 用c++释放内存的最好方法是什么

c - 制作 : command not found when specifying cross compiler path

c - 在c套接字编程中使用write发送缓冲区

ios - SwiftyJSON 转换为多个字符串数组

arrays - Swift 泛型和子类

c - 以通用方式安全地初始化 C 中的数组

c - 从以子字符串开头的单词中删除子字符串。(C 语言)

java - 将数组插入二维数组

C编程指针char数组