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); }
This is a discussion on Array Char to String with
Thread: Array Char to String with \0
within the C Programming forums, part of the General Programming Boards category; Hi,
I need convert, a Char Array to string, and i dont know if it has 0.
Code:
void charArrToStr()
...
Array Char to String with \0
Hi,
I need convert, a Char Array to string, and i dont know if it has 0.
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.
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))"
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 at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.
Totally agree with salem for ' printf(aux);'
Use it if you want format string attack?
Recent additions
Similar Threads
Code review
[Inheritance Hierarchy] User Input on program with constructors. How ?
Personal Program that is making me go wtf?
Unknown Memory Leak in Init() Function
Character arrays