int* asciiCode(char c1, char c2){
static int asciiCode[126];
/code/
/code/
return asciiCode;
}
对于这种情况,我可以使用分配而不是静态int吗?我不知道上面的指针数组元素的数目是多少?如果是的话,我该怎么做?如何使用动态分配而不是静态int?
int* asciiCode(char c1, char c2){
static int asciiCode[126];
/code/
/code/
return asciiCode;
}
对于这种情况,我可以使用分配而不是静态int吗?我不知道上面的指针数组元素的数目是多少?如果是的话,我该怎么做?如何使用动态分配而不是静态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
'我可以可以使用allocation'..what分配?动态?为什么? –
_请澄清您的具体问题或添加额外的细节,以确切地突出你所需要的。正如目前所写,很难确切地说出你在问什么。请参阅如何寻求问题页面以获得澄清此问题的帮助._ –
是的,动态分配,对此感到抱歉 –