|
|
View previous topic :: View next topic |
Author |
Message |
cvargcal
Joined: 17 Feb 2015 Posts: 134
|
load string from array |
Posted: Thu Apr 30, 2020 12:50 pm |
|
|
Hi, I did this function for 1 database
Code: | #include <stdio.h>
const char db1[3][50]={
"cvargcal/feeds/testv\0", // index 0
"cvargcal/feeds/monitor\0", // index 1
"cvargcal/feeds/control1\0" // index 2
};
const char db2[3][50]={
"cvargcal/feeds1\0", // index 0
"cvargcal/feeds2\0", // index 1
"cvargcal/feeds3\0" // index 2
};
char *load_dat( int index){
char *r = (char*)malloc(50);
strcpy(r, "");
int i=0;
while((db1[index][i]!=NULL)&&(i<50)){
r[i]=db1[index][i];
i++;
}
r[i]='\0';
return r;
}
int main()
{
printf(">> %s",load_dat(0));
return 0;
} |
but I want a function for load data from any db, like load_dat(db_x,index_x), I dont know how to declare load_dat char **array[index][50] |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Fri May 01, 2020 12:45 am |
|
|
The silly thing is you are already using a function that is capable of doing
this, but are then going DIY....
strcpy, is capable of copying the string from the const array to RAM,
more efficiently than the DIY code.
All it needs is the address of the start of the source string.
So:
strcpy(r, &db1[index][0]);
will copy the 'index' entry from db1 to r.
strcpy(r, &db2[index][0]);
will copy the index entry from db2.
You need the compiler option:
#device PASS_STRINGS=IN_RAM
otherwise there will be a complaint about using the pointer on the
const string.
Your code as posted has the major 'issue', that a new memory buffer
will be generated by malloc every time it is called. A single fixed buffer,
or a 'free' before the next time it is used is needed, or you will quickly
run out of memory.
The call to strcpy, could easily be made a macro, called with the
name of the required database. |
|
|
cvargcal
Joined: 17 Feb 2015 Posts: 134
|
|
Posted: Fri May 01, 2020 7:54 pm |
|
|
Ttelmah wrote: | The silly thing is you are already using a function that is capable of doing
...
|
Yes, this help me.... thanks you! |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|