-
HW Question
Write a function that initializes all elements of
a character array to blanks. The function should take
two arguments. The first is a pointer to a character
array. The second is the number of elements in the
array. DO NOT USE BRACES '[' or ']' IN YOUR SOLUTION.
This is what I have does it look right?:
void blank (void)
{
char buff[50];
char *ptr;
ptr = buff;
*ptr = '\0';
puts (buff);
}
Thanks mattz
-
void blank(void)....
the problem states the function should take 2 arguments, so your function should be of the general form
return_type function_name(arg1_type arg1, arg2_type arg2)
Also, the question says do not use braces.... so buff[50] I'm guessing won't be acceptable...
Hope that helps.
-
Hi,
homework question ... again? ;°)=)
I'd advice you to check your books, it's a simple task, really.
Just think a little bit about!
- What's the difference between * and & ?
- What kind of function do you need?
- What should that function return?
- How can you pass arguments to a function?
- Which one of the arguments should be a const?
etc.
Have fun, and ask, if you run in *real* problems!
-
Here is what I HAVE..I did READ btw.
#include <stdio.h>
int blanks ( char* a, int num );
int main (void)
{ int x;
char buff[20];
char *buff_ptr;
buff_ptr = buff;
for (x=0; x < 5; x++)
blanks (buff_ptr, x);
return 0;
}
int blanks ( char *a, int num)
{
int i;
for (i = 0 ; i < num ; i++)
a[i] = '\0';
for (i = 0 ; i < num ; i++)
printf("%s\n",a[i]);
return 0;
}
Not sure if its valid...seems to have issues.
-
'\0' is normall seen as the end of a string... if you set every value to that in your string I'm guessing when you try to show it you will have an "empty" string. I would make it a space (' ') instead, and then probably add a '\0' onto the end.
You can avoid braces (a[i]) by using a pointer to move across the passed array...
char *ptr;
//set ptr to "point" at the first character in the string
//move across the string using the ptr
//set the value pointed to by that address to ' '
(for ptr = a, i = 0; i < num; i++, ptr++)
*ptr = ' ';
... or something like that... it's been a while...
Finally, I think it might be a good idea to initialize buff[20] in main to something to help you debug...
-
ANSWER
Thanks to all,
For those interested here is the answer:
#include <stdio.h>
int blanks ( char* a, int num );
int main (void)
{ int y;
int x =5;
char buff[5];
char *buff_ptr;
buff_ptr = buff;
//(x=0; x < 5; x++)
blanks (buff_ptr, x);
for (y=0; y < 5; y++)
printf("%c\n", buff[y]);
return 0;
}
int blanks ( char *a, int num)
{
int i;
for (i = 0 ; i < num ; i++)
*(a+i)= ' ';
return 0;
}
Mattz
-
Here's a better way:
memset( myBuf, ' ', sizeof( myBuf ) );
Quzah.
-
Wow...you are good :)
Thanks for help.