I'm trying to create a function that will receive an array of strings and the size and will return a string made of the biggest ASCII value's letter of each word, and the size of the string has to be precised and I'm not allowed using operator [](which is my main issue).
so for:
char *strArr[SIZE] = { "hello", "and", "good", "morning" };
the function shall return a string with the word
"onor"
.
So i thought of creating a double for loop, first one will lead me into the location of each word in the array and the inside one will help me go through each word.
currently I'm having trouble finding the right format with my pointers to actually go through the letters of my first word.
I'm aware i haven't checked if my memory allocation is valid and also didn't free my memory yet as I'm trying to figure out whats wrong first.
char *bigLetters(char *str[], int size)
{
char *strNew = (char *)malloc((size + 1) * sizeof(char));
char max = 'a';
for (int i = 0; i < size; i++)
{
for (int j = 0; (*(str + i)+j) != NULL; j++)
{
if ((*(str + i) + j) >= max)
{
max = (*(str + i) + j);
}
}
*(strNew + i) = max;
}
*(strNew +(size+1)) = NULL;
return *(strNew);
}
void main()
{
char *strArr[SIZE] = { "hello", "and", "good", "morning" };
char *res = bigLetters(strArr, SIZE);
printf("The new string is --> %s\n", res);
system("pause");
}
It will be easier to use the pointers if you separate the string pointer from its character pointer. Also, the max needs to be reset for each string, and you were writing the final string terminator outside of the memory allocated. You also use NULL where you should be using the character '\0'.
Finally the function was returning the first character of the new string (which I later free).
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
char *bigLetters(char *str[], int size)
{
char *strNew = malloc(size + 1); // no cast or sizeof necessary
for (int i = 0; i < size; i++)
{
char ch;
char max = 'a'; // moved inside loop
char *ptr = *(str + i); // use a separate pointer
for (int j = 0; (ch = *(ptr + j)) != '\0'; j++) // pull out the character
{
if (ch > max) // >= is not necessary
{
max = ch;
}
}
*(strNew + i) = max;
}
*(strNew + size) = '\0'; // correct the bounds error
return strNew; // just the pointer not its target
}
int main(void) // correct signature
{
char *strArr[SIZE] = { "hello", "and", "good", "morning" };
char *res = bigLetters(strArr, SIZE);
printf("The new string is --> %s\n", res);
free(res); // clean up
system("pause");
}
Program output
The new string is --> onor
Press any key to continue . . .
If you didn't impose odd and unhelpful restrictions upon your coding, you'd be able to quickly see the problems with your code or even avoid making them in the first place. The problem is that the following statement makes no sense - you're comparing a char * with a char as you're only de-referencing str once.
if ((*(str + i) + j) >= max)
This is the same as writing
if ((str[i] + j) >= max)
which you can see the obvious mistake since what you're trying to write is the equivalent of
if ((str[i][j]) >= max)
which would be
if (*(*(str + i) + j) >= max)
Your compiler should be throwing up warnings because comparing between a pointer and an integer is rarely something you'd want to do.
You can use pointers as position indicators and advance them as needed.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
char
biggest_ascii(char* str)
{
char c = 0;
int i;
for (i = 0; *str; str++)
if (*str > c)
c = *str;
return c;
}
int
main()
{
int i;
char* strArr[SIZE] = {"hello", "and", "good", "morning"};
char** ppch;// current string
char res_str[SIZE + 1] = {0};/* resulting string,
initilized to 0 to be 0-terminated */
char* pch;// current char position
for (i = 0, ppch = strArr, pch = res_str; i < SIZE; i++, ppch++, pch++)
*pch = biggest_ascii(*ppch);
printf("%s\n", res_str);
return 0;
}
First, (*(str + i)+j) isn't the good way.
You could replace all
(*(str + i) + j)
by :
str[i][j]
Then, you need to reset the max to "a", because it's 'o' when you leave the loop, so your condition become str[i][j] >= o which is not what you want. Do it before the second for.
And I would have used while instead of for for the first loop.
I edited your code and this version is working fine for me :
#include <stdlib.h>
char *bigLetters(char *str[], int size)
{
char *strNew = (char *)malloc((size + 1) * sizeof(char));
int i = 0;
while (i < size) {
char max = 'a';
for (int j = 0; str[i][j]; j++) {
if (str[i][j] >= max) {
max = str[i][j];
}
}
strNew[i] = max;
i++;
}
strNew[i] = '\0';
return strNew;
}
void main()
{
char *strArr[5] = { "hello", "and", "good", "morning"};
char *res = bigLetters(strArr, 4);
printf("The new string is --> %s\n", res);
return 0;
}
str[i] is equivalent to *(str + i) and str[i][j] is equivalent to *(*(str + i) + j).
In your code you are using (*(str + i) + j) which is incorrect.
When char *[] passed to function, it will decay to char **. So, in bigLetters(), you can give char **str as the parameter. Also, it is inline with you requirement - not allowed using operator [].
Instead of hardcoding the dimension SIZE in char *strArr[SIZE], you can give the empty [] and let the compiler assign the dimension based on the size of initializer. In your case, size of initializer is 4 as you have given 4 strings in the strArr initializer. You can compute the size of strArr like this:
sizeof(strArr)/sizeof(strArr[0]);
You can do:
#include <stdio.h>
#include <stdlib.h>
char *bigLetters(char **str, size_t size) {
char *strNew = calloc(size + 1, 1); // sizeof(char) is always 1
// calloc will initialize all bytes in the allocated storage to zero.
// You dont need to add the null terminating character at the end of strNew
if (strNew == NULL)
exit(EXIT_FAILURE);
for (size_t i = 0; i < size; i++) {
for (size_t j = 0; *(*(str + i)+j) != '\0'; j++) {
if (*(*(str + i) + j) > *(strNew + i)) {
// You can directly fill the allocated memory with biggest ASCII
*(strNew + i) = *(*(str + i) + j);
}
}
}
return strNew;
}
int main(void) {
char *strArr[] = { "hello", "and", "good", "morning" };
char *res = bigLetters(strArr, sizeof(strArr)/sizeof(strArr[0]));
if (res != NULL) {
printf("The new string is --> %s\n", res);
free (res);
}
else
printf("bigLetters returned NULL\n");
return 0;
}
Note that void return type main() is not as per standard. Instead, you should use int as return type of main().
Related
I'm trying to solve a challenge, but I have no idea of what's wrong with my code!
The challenge is:
Create a function that splits a string of characters into words.
Separators are spaces, tabs and line breaks.
This function returns an array where each box contains a character-string’s address represented by a word. The last element of this array should be equal to 0 to emphasise the end of the array.
There can’t be any empty strings in your array. Draw the necessary conclusions.
The given string can’t be modified.
Note: The only allowed function is malloc()
The bug/problem:
I faced this problem and I tried to solve it but I wasn't able to identify what's wrong.
I created a function named split_whitespaces() to do the job.
When I print the array of strings inside of the split_whitespaces function, I get the following output:
Inside the function:
arr_str[0] = This
arr_str[1] = is
arr_str[2] = just
arr_str[3] = a
arr_str[4] = test!
And when I print the array of string inside the main function, I get the following output:
Inside the main function:
arr_str[0] = #X#?~
arr_str[1] = `X#?~
arr_str[2] = just
arr_str[3] = a
arr_str[4] = test!
I created a function word_count to count how many words in the input string so I can allocate memory using malloc and with word_count + 1 (null pointer).
int word_count(char *str) {
int i;
int w_count;
int state;
i = 0;
w_count = 0;
state = 0;
while (str[i]) {
if (!iswhitespace(str[i])) {
if (!state)
w_count++;
state = 1;
i++;
} else {
state = 0;
i++;
}
}
return (w_count);
}
And another function called strdup_w to mimic the behavior of strdup but just for single words:
char *strdup_w(char *str, int *index) {
char *word;
int len;
int i;
i = *index;
len = 0;
while (str[i] && !iswhitespace(str[i]))
len++, i++;;
word = (char *) malloc(len + 1);
if (!word)
return (NULL);
i = 0;
while (str[*index]) {
if (!iswhitespace(str[*index])) {
word[i++] = str[*index];
(*index)++;
} else
break;
}
word[len] = '\0';
return (word);
}
Here's my full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **split_whitespaces(char *str);
char *strdup_w(char *str, int *index);
int word_count(char *str);
int iswhitespace(char c);
int main(void) {
char *str = "This is just a test!";
char **arr_str;
int i;
i = 0;
arr_str = split_whitespaces(str);
printf("\nOutside the function:\n");
while (arr_str[i]) {
printf("arr_str[%d] = %s\n", i, arr_str[i]);
i++;
}
return (0);
}
char **split_whitespaces(char *str) {
char **arr_str;
int i;
int words;
int w_i;
i = 0;
w_i = 0;
words = word_count(str);
arr_str = (char **)malloc(words + 1);
if (!arr_str)
return (NULL);
printf("Inside the function:\n");
while (w_i < words) {
while (iswhitespace(str[i]) && str[i])
if (!str[i++])
break;
arr_str[w_i] = strdup_w(str, &i);
printf("arr_str[%d] = %s\n", w_i, arr_str[w_i]);
w_i++;
}
arr_str[words] = 0;
return (arr_str);
}
char *strdup_w(char *str, int *index) {
char *word;
int len;
int i;
i = *index;
len = 0;
while (str[i] && !iswhitespace(str[i]))
len++, i++;;
word = (char *)malloc(len + 1);
if (!word)
return (NULL);
i = 0;
while (str[*index]) {
if (!iswhitespace(str[*index])) {
word[i++] = str[*index];
(*index)++;
} else
break;
}
word[len] = '\0';
return (word);
}
int word_count(char *str) {
int i;
int w_count;
int state;
i = 0;
w_count = 0;
state = 0;
while (str[i]) {
if (!iswhitespace(str[i])) {
if (!state)
w_count++;
state = 1;
i++;
} else {
state = 0;
i++;
}
}
return (w_count);
}
int iswhitespace(char c) {
if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
return (1);
return (0);
}
I'm sorry, if anything this is my first time trying to seek help.
There are multiple problems in the code:
the size is incorrect in arr_str = (char **)malloc(words + 1); You must multiply the number of elements by the size of the element:
arr_str = malloc(sizeof(*arr_str) * (words + 1));
it is good style to free the array in the main() function after use.
the test while (iswhitespace(str[i]) && str[i]) is redundant: if w_count is computed correctly, testing str[i] should not be necessary. You should use strspn() to skip the white space and strcspn() to skip the word characters.
if (!str[i++]) break; is completely redundant inside the loop: str[i] has already been tested and is not null.
while (str[i] && !iswhitespace(str[i])) len++, i++;; is bad style. Use braces if there is more than a single simple statement in the loop body.
the last loop in strdup_w is complicated, you could simply use memcpy(word, str + *index, len); *index += len;
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
char **split_whitespaces(const char *str);
char *strdup_w(const char *str, int *index);
int word_count(const char *str);
int iswhitespace(char c);
int main(void) {
const char *str = "This is just a test!";
char **arr_str;
int i;
arr_str = split_whitespaces(str);
if (arr_str) {
printf("\nOutside the function:\n");
i = 0;
while (arr_str[i]) {
printf("arr_str[%d] = %s\n", i, arr_str[i]);
i++;
}
while (i --> 0) {
free(arr_str[i]);
}
free(arr_str);
}
return 0;
}
char **split_whitespaces(const char *str) {
char **arr_str;
int i;
int words;
int w_i;
i = 0;
w_i = 0;
words = word_count(str);
arr_str = malloc(sizeof(*arr_str) * (words + 1));
if (!arr_str)
return NULL;
printf("Inside the function:\n");
while (w_i < words) {
while (iswhitespace(str[i]))
i++;
arr_str[w_i] = strdup_w(str, &i);
if (!arr_str[w_i])
break;
printf("arr_str[%d] = %s\n", w_i, arr_str[w_i]);
w_i++;
}
arr_str[words] = NULL;
return arr_str;
}
char *strdup_w(const char *str, int *index) {
char *word;
int len;
int start;
int i;
i = *index;
start = i;
while (str[i] && !iswhitespace(str[i])) {
i++;
}
*index = i;
len = i - start;
word = malloc(len + 1);
if (!word)
return NULL;
i = 0;
while (i < len) {
word[i] = str[start + i];
i++;
}
word[i] = '\0';
return word;
}
int word_count(const char *str) {
int i;
int w_count;
int state;
i = 0;
w_count = 0;
state = 0;
while (str[i]) {
if (!iswhitespace(str[i])) {
if (!state)
w_count++;
state = 1;
} else {
state = 0;
}
i++;
}
return w_count;
}
int iswhitespace(char c) {
return (c == ' ' || c == '\t' || c == '\n' || c == '\r');
}
From my top comment ...
In split_whitespaces, try changing:
arr_str = (char **) malloc(words + 1);
into:
arr_str = malloc(sizeof(*arr_str) * (words + 1));
As you have it, words is a count and not a byte length, so you're not allocating enough space, so you have UB.
UPDATE:
But watched some tutorials and they said that malloc takes one argument which is the size of the memory to be allocated (in bytes), that's why I allocated memory for 5 bytes! can you please tell my an alternative of using malloc without sizeof() function. I'll appreciate it. – Achraf EL Khnissi
There's really no clean way to specify this without sizeof.
sizeof is not a function [despite the syntax]. It is a compiler directive. It "returns" the number of bytes occupied by its argument as a compile time constant.
If we have char buf[5];, there are 5 bytes, so sizeof(buf) [or sizeof buf] is 5.
If we have: int buf[5];, there are 5 elements, each of size int which is [typically] 4 bytes, so the total space, in bytes, is sizeof(int) * 5 or 4 * 5 which is 20.
But, int can vary depending on the architecture. On Intel 8086's [circa the 1980's], an int was 2 bytes (i.e. 16 bits). So, the above 4 * 5 would be wrong. It should be 2 * 5.
If we use sizeof(int), then sizeof(int) * 5 works regardless of the architecture.
Similarly, on 32 bit machines, a pointer is [usually] 32 bits. So, sizeof(char *) is 4 [bytes]. On a 64 bit machine, a pointer is 64 bits, which is 8 bytes. So, sizeof(char *) is 8.
Because arr_str is: char **arr_str, we could have done:
arr_str = malloc(sizeof(char *) * (words + 1));
But, if the definition of arr_str ever changed (to (e.g.) struct string *arr_str;), then what we just did would break/fail if we forgot to change the assignment to:
arr_str = malloc(sizeof(struct string) * (words + 1));
So, doing:
arr_str = malloc(sizeof(*arr_str) * (words + 1));
is a preferred idiomatic way to write cleaner code. More statements will adjust automatically without having to find all affected lines of code manually.
UPDATE #2:
You might just add why you removed the (char **) cast :) -- chqrlie
Note that I removed the (char **) cast. See: Do I cast the result of malloc?
This just adds extra/unnecessary "stuff" as the void * return value of malloc can be assigned to any type of pointer.
If we forgot to do: #include <stdlib.h>, there would be no function prototype for malloc, so the compiler would default the return type to int.
Without the cast, the compiler would issue an an error on the statement [which is what we want].
With the cast, this action is masked at compile time [more or less]. On a 64 bit machine, the compiler will use a value that is truncated to 32 bits [because it thinks malloc returns a 32 bit value] instead of the full 64 bit return value of malloc.
This truncation is a "silent killer". What should have been flagged as a compile time error produces a runtime fault (probably segfault or other UB) that is much harder to debug.
This question already has answers here:
Sizeof vs Strlen
(4 answers)
Closed 3 years ago.
I have simple function that should connect string but in different way.
If i have one string "abc" and another "123" final string should be "a1b2c3".
Here is code
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
char *connStrings(char *s1, char *s2) {
int s1L, s2L,i = 0,k=1,j=0;
s1L = sizeof(s1);
s2L = sizeof(s2);
char* result = (char*) malloc((s1L + s2L));
while (s1[i] != '\0') {
result[j] = s1[i++];
j = j + 2;
}
i = 0;
while (s2[i] != '\0') {
result[k] = s2[i++];
k = k + 2;
}
result[s1L + s2L] = '\0';
printf("\n %s \n", result);
}
int main() {
connStrings("abcdefghi","123456789");
}
So what's the problem?
the final output of this program is still the same "a1b2c3d4e5f6g7h8"
It ignores i and 9 somehow. Even if I add more chars into both strings it still prints the same
"a1b2c3d4e5f6g7h8". I will be thankful for any help or advice.
Use proper function return type and strlen instead of sizeof
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void connStrings(char *s1, char *s2) {
int s1L, s2L, i = 0, k = 1, j = 0;
s1L = strlen(s1);
s2L = strlen(s2);
char *result = (char *) malloc((s1L + s2L + 1 )); // extra one for the `null` terminator `\0`
while (s1[i] != '\0') {
result[j] = s1[i++];
j = j + 2;
}
i = 0;
while (s2[i] != '\0') {
result[k] = s2[i++];
k = k + 2;
}
result[s1L + s2L + 1] = '\0';
printf("\n %s \n", result);
// free memory when you're done
free(result);
}
int main() {
connStrings("abcdefghi", "123456789");
return 0; // or use void
}
When you pass an array as an argument to a function, what you're really passing is a pointer to the first element of the array.
sizeof will not return the length of the buffer in this case, but the size of a pointer.
Fortunately, C strings have the useful property of being terminated with a null character ('\0'), which allows functions like strlen to give you the actual length of the string, even when all you have is a pointer and not the array. strlen works similar to this:
size_t strlen(char *s)
{
size_t ret = 0;
while(*s) ret++, s++;
return ret;
}
Even when calculating the length of a string when you have an actual array, you still shouldn't use sizeof because that will return the entire size of the buffer, which may not be the length of the string within it.
Consider: char s[100] = "Hello World";
sizeof s would be 100; strlen(s) would return 11.
I have this code, and I want from a string that is stored in value called original such as home$family$fun, using the delimiter value such as $, assign to another string named final the word between the two delimiters. That means that final should contain family and print the result from main. But the operation must be done in another function using only pointer and pointer arithmetic. Also the prototype of the getPart function must not be changed.
My problem is that, I get this result to my variable final when I am inside the getPart function but when I am returning to main the final function have only '\0' as value and not the value I wanted it. I think, the problem is something with the addresses, meaning that if the value which string's address change, then the value of string will be changed. But I am a bit confused...Could someone help me?
#include <stdio.h>
#include <string.h>
#define SIZE 32
int getPart(char original[], char delimiter[], char final[]) {
int i, j;
int counter = 0;
int counter1 = 0;
for(i = 0; *(original + i) != '\0'; i++) {
if(*(original + i) == *delimiter) {
counter++;
}
}
if(counter > 1) {
for(i = 0; *(original + i) != '\0'; i++) {
if(*(original + i) == *delimiter) {
if(counter1 < 1) {
final = (original + i + 1);
counter1++;
}
else {
for(j = 0; *(final + j) != '\0'; j++) {
if(strcmp(final + j,original + i) == 0) {
*(final + j) = '\0';
*(final + j + 1) = '\0';
//final + j = '\0';
}
}
}
}
}
return(1);
}
else {
return(0);
}
}
int main(int argc, char *argv[]) {
char original[SIZE], delimiter[SIZE], final[SIZE];
char format_str_or[20], format_str_del[20];
int counter, i;
for(i = 0; i < SIZE; i++) {
*(final + i) = '\0';
}
sprintf(format_str_or," %%%ds",SIZE - 1);
printf("Enter string: ");
scanf(format_str_or,original);
sprintf(format_str_del," %%%ds", SIZE - 1);
printf("Enter delimiter: ");
scanf(format_str_del,delimiter);
counter = getPart(original,delimiter,final);
printf("%d\n",counter);
if(counter == 1) {
printf("%s\n",final);
}
else if(counter == 0) {
printf("%s does not appear twice in %s\n",delimiter,original);
}
return(0);
}
Two problems:
In your function you reassign the pointer final to point somewhere into original. Reassignment won't work as the pointer is passed by value, and the assignment only changes the local variable.
By modifying contents of final you also modify the contents of original.
Both these issues could be solved by copying to final instead of reassigning where it points.
Both these issues should also be easily detectable using standard debugging practices.
I've written a function called safecat that adds one string (called ct) to the end of another string (called s).
The resulting new s is then returned.
In the main function my task is to check if my function worked the intended way, and if so, then print the result of my function safecat.
The problem I have is that when I assign the return value of safecat to another char-string (in this case str) in my main function, the stuff in str which comes from ct is just garbage.
I don't understand where the problem is, if I just do printf("%s", safecat(s, ct)); I get the correct result.
Here you see my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *safecat(char *s, const char *ct);
int main()
{
char s[] = "Twin";
const char ct[] = "Peaks";
char *str = safecat(s, ct);
if(str == NULL){
printf("Error in function!");
return 1;
}
printf("\n%s\n", str);
return 0;
}
char *safecat(char *s, const char *ct){
int i, k, j = 0;
int max_count = strlen(s) + strlen(ct) + 1;
for(i = strlen(s); i < max_count; i = i + sizeof(char)){
*(s + i) = (char *) malloc((strlen(s) + strlen(ct) + 1) * sizeof(char));
if(!(s + i)){
for(k = strlen(s) / sizeof(char); k < i; k++){
free(*(s + k));
}
return NULL;
}
*(s + i) = *(ct + j);
j++;
}
return s;
}
I think the error happens when I assign safecat to str.
When I print out str I get "TwinP' a" instead of "TwinPeaks".
Thanks for helping!
You can not change the size of the array
char s[] = "Twin";
in the function using malloc.
And in any case this loop
for(i = strlen(s); i < max_count; i = i + sizeof(char)){
*(s + i) = (char *) malloc((strlen(s) + strlen(ct) + 1) * sizeof(char));
if(!(s + i)){
for(k = strlen(s) / sizeof(char); k < i; k++){
free(*(s + k));
}
return NULL;
}
*(s + i) = *(ct + j);
j++;
}
does not make sense. For example the expression *(s + i) has type char instead of the type char *. And also it is not clear why a memory is allocated in each iteration of the loop.
A correct approach is to allocate dynamically a new array with the size equal to the sum of the sizes of the source arrays plus one and to copy the source arrays in the allocated array.
Here is a demonstrative program that shows how it can be done. Also you should free the allocated memory when the array is not needed any more.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * safecat(const char *s1, const char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2) + 1);
if (result != NULL)
{
char *p = result;
while (*s1) *p++ = *s1++;
do { *p++ = *s2; } while (*s2++);
}
return result;
}
int main( void )
{
char s[] = "Twin";
char ct[] = "Peaks";
char *str = safecat(s, ct);
if (str == NULL)
{
puts("Error in function!");
return 1;
}
puts(str);
free(str);
return 0;
}
The program output is
TwinPeaks
Of course you could use standard string functions strcpy and strcat instead of the loops that can be both written even in the return statement
return result == NULL ? result : strcat( strcpy( result, s1 ), s2 );
I think that you misunderstand the meaning of malloc.
You are using malloc as if it would make a new slot in or at the end of a string. malloc(sizeX), however, reserves a new memory block with sizeX bytes somewhere in the memory (rather than at a particular position that you could determine). And the result of malloc is a pointer to a memory block, not a character.
So what you do with expression *(s + i) = (char *) malloc((strlen(s) + strlen(ct) + 1) * sizeof(char)); is actually writing a pointer value (usually something obscure when viewed as characters) as value directly into string s at the position of s's string terminating character;
For your safecat, first reserve memory for the new concatenated result string, then fill it up with your logic (I suppose this is a programming assignment and you are not allowed to use strcpy, right?
int slen = strlen(s);
int ctlen = strlen(ct);
char *result = (char *) malloc((slen + ctlen + 1) * sizeof(char));
for (int i=0; i<slen; i++)
result[i] = s[i];
for (int i=0; i < ctlen + 1 ; i++) // note "i < ctlen + 1" for considering string terminator of ct.
result[i+slen] = ct[i];
When you copy the new string to the old string you wind up putting in the null character after the initial P. What you need to do is as follows.
malloc a new buffer (ns) of the size of maxcount.
strcpy s into ns
strcpy ct into ns + strlen(s)
Note. If you are not allowed to used strcpy(), then write your own version as a function safecpy() in the a similar fashion to safecat()
return ns
Note that you would want to free ns sometime later in the program if you no longer need it.
Thank you to everyone who helped. It was a coding assignment and I was able to figure it out the next day.
The stuff I've written must have seemed to be very chaotic as I've just learned about pointers, and yes, I was not allowed to use 'strcat()' or 'strcpy()'.
What I'm trying to achieve -
Input: (String literal assumed.) This is a string
Output: string a is This
My naive solution:
Copy the string literal to an char array.
Current contents of the char array str[sizeofstring] : This is a string
Reverse the array word by word and store it in another array.
char reverse[sizeofstring]: sihT si a gnirts
Traverse array reverse from the last to the 0th position. Store it in char array solution.
char solution[sizeofstring]: string a is This
strcpy(pointertoachar, solution). - Because the function needs to return a pointer to char.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *reverse(char *input) {
int n = strlen(input);
char str[n];
char reverse[n];
char solution[n];
char *solutionp = malloc(sizeof(char) * n);
strcpy(str, input);
int last = 0;
int i = 0;
int q = 0;
while (str[i] != '\0') {
if (str[i] == ' ') {
printf("i : %d\n", i);
printf("LAST:%d\n", last);
for (int t = (i - 1); t >= last; t--) {
reverse[q] = str[t];
q++;
}
last = i + 1;
reverse[q] = ' ';
q++;
}
i++;
}
// for the last word.
for (int cc = i - 1; cc >= last; cc--) {
reverse[q] = str[cc];
q++;
}
// Traversing from the last index to the first.
int ii;
int bb = 0;
for (ii = n - 1; ii >= 0; ii--) {
solution[bb] = reverse[ii];
bb++;
}
// This prints the right output.
// printf("%s\n",solution);
// Copying from a char array to pointer pointing to a char array.
strcpy(solutionp, solution);
return solutionp;
}
int main() {
char *str = "This is a string";
char *answer;
answer = reverse(str);
printf("%s\n", answer);
printf("\n");
return 0;
}
The problem:
Steps 1 to 3 are working as intended. For debugging purpose, I tried printing the output of the array which contains the solution and it worked, but when I copy it to char array pointed by a pointer using strcpy and return the pointer, it prints garbage values along with partially right output.
OUTPUT:
string a is This??Z??
There seems to be some problem in step 4. What am I doing wrong?
The major problem in your code is you allocate your temporary buffers one byte too short. You must make enough room for the final '\0' byte at the end of the strings.
You can simplify the code by using an auxiliary function to copy a block in reverse order:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *reverse_block(char *dest, const char *src, int len) {
for (int i = 0; i < len; i++) {
dest[i] = src[len - i - 1];
}
dest[len] = '\0';
return dest;
}
char *reverse_words(const char *string) {
int i, last;
int len = strlen(string);
char temp[len + 1];
for (i = last = 0; i < len; i++) {
if (string[i] == ' ') {
// copy the word in reverse
reverse_block(temp + last, string + last, i - last);
temp[i] = ' ';
last = i + 1;
}
}
// copy the last word in reverse
reverse_block(temp + last, string + last, len - last);
// allocate an array, reverse the temp array into it and return it.
return reverse_block(malloc(len + 1), temp, len);
}
int main(void) {
const char *string = "This is a string";
printf("%s\n", string);
char *solution = reverse_words(string);
printf("%s\n", solution);
free(solution);
return 0;
}
Now you can improve the code further by implementing a function that reverses a block in place. With this, you no longer need a temporary buffer, you can work on the string copy directly and it simplifies the code.