if you insist on pointers,
what you have above is correct as far as I can tell. what does it do?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
char * char_repeat( int n, char c ) //a subroutine that takes how many and what char and returns the "string"
{
char * dest = malloc(n+1); //allocate N+1 memory locations; the +1 is for the special null terminal (c-strings end in the special ascii value zero)
memset(dest, c, n); //set ALL the locations from 0 to n as the value in c/
dest[n] = '\0'; //append the special zero terminal character
return dest; //return the complete string.
}
int main() { //a main program that exercises the above subroutine.
char * result = char_repeat(5, '*');
char * a80 = char_repeat(80, 'a'); //you want this.
puts(result);
free(result); //give back the memory to the OS. Modern OS do this for you anyway on program exit, which is up next, but its best practice to do it yourself, and critical to do it yourself in large programs that need to use the space for something else before the program ends.
return 0;
}
if you are using a c++ compiler you MUST cast the result of malloc. If its a true C compiler, I don't think it cares (cant remember). It won't hurt in C...
char * dest = (char*) malloc(... //the cast is the (char*)
Thank you all for your help. I thought I was compiling using GCC, but it appears I was using g++ , so trying to compile as C++. It didn't like it. It does work using Pelles C.