gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:35:48 24 4
gpt4 key购买 nike

 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com