Hi,
I need convert, a Char Array to string, and i dont know if it has 0.
Code:void charArrToStr()
{
char aux[30];
char * teste;
memset(teste, 0, 30);
teste[0] = 't';
teste[1] = 'e';
teste[2] = 's';
strcpy(aux, teste);
printf(aux);
}
Printable View
Hi,
I need convert, a Char Array to string, and i dont know if it has 0.
Code:void charArrToStr()
{
char aux[30];
char * teste;
memset(teste, 0, 30);
teste[0] = 't';
teste[1] = 'e';
teste[2] = 's';
strcpy(aux, teste);
printf(aux);
}
you need to allocate memory for teste before you use it.
If you had an array of chars, you could make it a string by adding a '\0' at the end of it.
That is a pointer to char. Depending on your system, doing sizeof(teste) will get you either 4, or 8 bytes*. There is nowhere near 30 bytes to play with there. I think you are confused about the difference between pointers and arrays. Read through some of these questions and answers - hopefully it will clarify the difference between a pointer and an array for you.Code:char * teste;
*: Assuming you are running an x86 or x86_64 machine, of course.
You might wish to use the strncpy function.
Tim S.
He is using that, but on a a pointer to char that has no memory malloc'd for it. So it fails anyway.
Also, among other things, printf(aux) doesn't work. Go read up on the proper way to call printf.
What's the cost of calling calloc instead of malloc? You may consider using calloc to get mem that is already zeroed. Just remember to allocate space for the '\0', something like "calloc(strlen(aux) + 1, sizeof(char))"
Using sizeof(x) even when you know what it's going to be is like using defines instead of magic numbers, it explains what the "1" would not. It's a personal preference, nothing more. Although it should be noted that using sizeof doesn't detract from performance, it's substituted for it's value at compile time.
One would think, given the convenience of zero filled memory, that malloc would rarely be used, and calloc would be preferred. Yet this is not generally the case. Have a look at the following from the C-FAQ:
It also gives a size_t value to calloc, which is what calloc expects.
> printf(aux);
NEVER pass variable string data to printf as the format string.
If anyone ever sneaks a % character in there, you're hosed!
Totally agree with salem for ' printf(aux);'
Use it if you want format string attack?