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); }
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.
Last edited by kermit; 07-21-2010 at 04:49 PM.
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))"
Hope is the first step on the road to disappointment.
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.
Last edited by kermit; 07-22-2010 at 04:09 PM.
> printf(aux);
NEVER pass variable string data to printf as the format string.
If anyone ever sneaks a % character in there, you're hosed!
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Totally agree with salem for ' printf(aux);'
Use it if you want format string attack?