malloc problem
Jan 29, 2015 at 6:45pm UTC
I would like some help for the following code. The output should be: hovercraft
but i get: Xovercraft instead.
I do not know if i messed up my code::blocks settings or simply i fail to spot the mistake :P
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#include <iostream>
#include <stdlib.h>
#include <cstring>
using namespace std;
void stringcopy(char *s1, char *s2);
int main()
{
int statusupdate;
char s[]="hovercraft" ;
char *ptr;
ptr =(char *) malloc(strlen(s)+1);// if i do not use (char*)
// my compiler says:
//error: cannot convert 'void (*)(char*, char*)' to 'const char*'
//for argument '1' to 'size_t strlen(const char*)'|
if (ptr==0)
statusupdate=1;
else
{
stringcopy(ptr,s);
cout << ptr;
free(ptr);
statusupdate=0;
}
return statusupdate;
}
void stringcopy(char *destination, char *source)
{
int i=0;
while (source[i++])
destination[i]=source[i];
destination[i]='\0' ;
}
Thanks...
Jan 29, 2015 at 6:55pm UTC
It actually has to do with your while loop:
while (source[i++]) //The increment is throwing your loop off
That will increment the value of i once its done testing it, and so when you finally copy an element, you're starting at source[1] instead of source[0].
I recommend moving the increment to the bottom of the loop instead; should make your code clearer and more easy to debug.
Hope that helps :)
Last edited on Jan 29, 2015 at 6:56pm UTC
Jan 29, 2015 at 9:45pm UTC
Thanks for the recommendations.
"code clearer and more easy to debug." I suppose you mean that i should use better names for variables, more spaces on each line .... etc ?
Jan 29, 2015 at 9:50pm UTC
I suppose you mean that i should use better names for variables, more spaces on each line .... etc ?
Little Captain was suggesting not doing this all on one line:
while (source[i++])
so when debugging it's easier to see the value of i before getting to the while condition test.
e.g.
1 2 3 4 5 6 7 8
int i=0;
while (source[i]) // <-- easier to see/debug what i is in the condition
{
destination[i]=source[i];
i++;
}
destination[i]='\0' ;
Last edited on Jan 29, 2015 at 9:52pm UTC
Topic archived. No new replies allowed.