I have to pass a c string into a char array, but if the string is larger then the char array size then it would copy the string array to the just the char array size then end it with a null character. Here is what I have so far.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
for (i = 0; s[i] != 80; i++)
if (s < 80)
s+1 = '\0';
Problem: I know i have to deference the string s and pass it into the char array, but I do not know how to put the limitation on it while putting a null character. I am stumped.
So in essence, you can treat a string like a character array, which will be very helpful in your for loop! Just remember to check both conditions that i is less than the number you need (for max copying and the terminating character) AND that the terminating character isn't present in your character array at that spot.
Or if you are trying to convert a character array into a string, this can be easily accomplished with the string concatanation (spelling?) operator: +, and a for loop.
What I was trying to do was pass a C string in to a char array. When I type the code s != 80 then that would increment the string until it was to the size 80. The next line of code if (s < 80) makes the C String S pass the string into the char array but adding a null character at the end.
I have passed C Strings into arrays before, but I just do not know how to make it where if hte string is more then 80 then the string only copies 79+null.
In C the normal* thing to do is use strcmp() and/or strncmp() to copy C-strings into another, I think what you're tasked to do is emulate strcmp(), but with limit check, i.e make a safer strcmp(), but easier to use than strncmp(), so probably you want to try this:
- get (declare) a C-string
- pass that string into a function that accepts C-strings
- and copy it into another C-string?
char* function_to_copy_one_string_into_another(constchar* original, char* copy, int size_of_copy);
I have passed C Strings into arrays before
then it'll also be good to remember that functions that accept arrays also need the size of the array
*i.e what the functions actually does is copy one array element to another, copy = str, etc
edit: arghh! I blame it on hunger pangs -for strcmp() read strcpy(), for strncmp() read strncpy() ;)