Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

how to implement a function in C

Status
Not open for further replies.

BMWE

Member level 2
Member level 2
Joined
Apr 4, 2005
Messages
51
Helped
1
Reputation
2
Reaction score
1
Trophy points
1,288
Activity points
1,585
Hello

given the following code:
Code:
void func(){
char *var=NULL;
str_cpy(var,"text1");
str_cpy(var,var+2);
some print(var) // result: xt1
some_free(var)
}

i should implement the str_cpy function.
how would you implement it efficiently (without memory leaks)?
 

That you wrote there will end in an error for sure since you are not allocating "var" before use. If not, the "some_free(var)" will.

The correct way should be:

Code:
void func(){
char var[32];   // 32 is arbitrary and may be any number larger than the size of "text1" + 1.
str_cpy(var,"text1");
str_cpy(var,var+2);
some_print(var) // result: xt1
}

strcpy: the simplest way you can do it is like the following **broken link removed** (replace __PSTRING with char*).
or you can add a third parameter and pass a maximum quantity of chars to copy.
 

That you wrote there will end in an error for sure since you are not allocating "var" before use. If not, the "some_free(var)" will.

The correct way should be:

Code:
void func(){
char var[32];   // 32 is arbitrary and may be any number larger than the size of "text1" + 1.
str_cpy(var,"text1");
str_cpy(var,var+2);
some_print(var) // result: xt1
}

strcpy: the simplest way you can do it is like the following **broken link removed** (replace __PSTRING with char*).
or you can add a third parameter and pass a maximum quantity of chars to copy.

but why to change the problem?
if i was able to change it, then i wouldn't apply for help
 

what? is a problem for school? why you can't change it?
I still believe it won't work because you are passing null, not even the pointer to a pointer.
So.........
Code:
#undef NULL
#define NULL   some_malloc(32)

// implement str_cpy as said before
// then the code you wrote at the beginning.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top