Thursday, July 30, 2009

What's wrong with my function in C?

void arrstrcpy(char *strdest, char *strsource, int index)


{


int i;


for (i = 0; i %26lt; strlen(strsource); i++)


{


strdest[index][i] = strsource[i];


}


}





I wanted to create a function that will copy a string to an index of an array of strings.. So i ended up in this piece of code.. My Dev-C compiler says it has an invalid argument passed on to the function.. By the way, the example I used is as follows:





char names[99][20], stemp[20];





strcpy(stemp, "Hello World");


arrstrcpy(names, stemp, i);





Please help me.. I didn't understand what my Compiler meant for the error... And if ever you know what's the better function for it, please tell me.. Thanks!! I really need it... (^^,)

What's wrong with my function in C?
Hi,





your function accepts pointers to strings, but you are passing with "names" an array of strings.





change your function declaration to





void arrstrcpy(char **strdest, char *strsource, int index)





which means with **strdest you pass a pointer to pointers (a pointer to an array of strings.








good luck


M.
Reply:"I wanted to create a function that will copy a string to an index of an array of strings"


There's a function that does it for you. It's in the string library. strcpy and strncopy





So you don't need a loop that copies character by character. Slow and inefficient. You're better off using the optimised strcopy that memory copies efficiently. We'll use strncopy because it's safer than strcopy.





I looked up the strncopy signature at http://cppreference.com/stdstring/strncp...





Hence, in your arrstrcopy, you want:





strncopy(strdest[index], strsource, sizeof strsource);





That's it. Actually, I don't know if this will work because I have no idea what your compiler is complaining about. I don't want paraphrasing. The compiler gives you a very specific error log. Post that and you get better help.





EDIT: And yes, what the guy above said. Your function signature is off.


No comments:

Post a Comment