假设我从数组 array[0] 开始。
当我遍历文本文件并找到关键字时,我想将这些词存储在该数组中。
所以第一次运行虽然我会非常简单地评估第一个关键字
数组[0] = "单词"
但是我不确定如何将该数组递增到 1 和 2,等等。
我读过一些关于内存分配的帖子,但那似乎是针对字符串的;也许我误解了这个概念。
我想保留当前数组的内容,并递增它。
我已经通过设置我的数组 [10] 来操纵它,但我更愿意学习正确的方法来做到这一点。
到目前为止我已经包含了下面的代码(没有任何内存分配)
#include <stdio.h>
#include <memory.h>
#include "tables.h"
int main() {
insertVarbleTble("Name","CSTRING",1,0,"");
return 0;
}
int insertVarbleTble(char *ident, char *type, int local, int constVar, char *constVal){
int successful;
int sizeArry;
sizeArry = sizeof(varible)/ sizeof(varible[0]);
if(sizeArry <= 0){
varible[sizeArry]== ident;
}else{
successful = (searchVarbleTble(ident,sizeArry)==1;
}
if(successful ==0){
varible[sizeArry+1]==ident;
}else{
printf("Already exists");
}
}
void realocMem(int size){
varible[size];
}
int searchVarbleTble(char * ident, int arrySize){
int i;
int results = 0;
for(i=0;i<arrySize;i++){
if(!strcmp(varible[i],ident)){
results= 1;
}
}
return results;
}
头文件包含我正在使用的数组,它们是:
char varible[0];
int insertVarbleTble(char *, char *, int, int , char *);
int searchVarbleTble(char *, int);
一个潜在的解决方案是先计算存在的关键字数量,然后对数组进行维数吗?
最佳答案
好吧,通常你想做的事用数组是不可能的。你的代码真的很难理解,但我会尝试给你一个例子来说明它是如何完成的。
这不是您想要的,但应该可以帮助您找到自己的解决方案。如果你想使用字符串,它会变得有点复杂,因为字符串本身就是数组,所以你必须确保你始终有足够的内存来存储当前可用的字符串。
#include <stdio.h>
#include <stdlib.h>
typedef struct data_container_{
int *mem;
int size;
} data_container;
void add_to_memory(data_container *data, int pos, int value)
{
if (pos+1 > data->size) //check if memory for this position is allocated
{
int *dummy = realloc(data->mem, pos+1); // call realloc to get more memory
if(dummy == NULL) //check if reallocation was succesful
{
puts("Memory reallocation failed");
exit(1); //terminate program
}
else
{
data->size = pos+1; //set size to the newly allocated size
data->mem = dummy; //if succesful point to the new memory location
}
}
data->mem[pos] = value;
}
int main(void)
{
data_container data; // create stuct
data.size = 2;
data.mem = malloc(sizeof (int) * data.size); //allocate memory, similar to an array but dynamic
if(data.mem == NULL) //check if allocation was succesful
{
puts("Memory allocation failed");
exit(1); //terminate program
}
add_to_memory(&data, 0, 3); //pass the address of the struct
add_to_memory(&data, 1, 6);
add_to_memory(&data, 2, 8); //now it uses realloc, pos would be out of the allocated range
for(int i =0; i<data.size; i++)
{
printf("%d\n",data.mem[i]); //a pointer can be accessed similar to an array
}
free(data.mem); //free the allocated memory
}
正如 Pablo 所说,您应该阅读有关 malloc
和 realloc
的内容,尤其是您应该记住分配的内存未初始化。 calloc
初始化为 0
。
永远记得释放不再使用的已分配空间。
关于c - C 中内存的重新分配 - 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49909934/