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/