how to reverse a string using array of pointers? - c

I want to reverse a string(user gives at runtime) using array of pointers,malloc and not by using array of characters. Can anybody help me by giving me a code? I am very new to C. Thanks in advance.

I am not sure what you are asking, But the following program meets your conditions,
1. there is array of pointers
2. there is malloc
3. there is no character array
#include <stdio.h>
#include <stdlib.h>
#define STR_MAX_SIZE 256
int main()
{
char *str;
char *pos[2];
char c;
if((str = malloc(STR_MAX_SIZE)) ==NULL) {
return -1;
}
scanf("%s",str);
pos[0] = str;
pos[1] = str;
while(*pos[1]) {
pos[1]++;
}
pos[1] -= 1;
while(pos[0] < pos[1]) {
c = *pos[0];
*pos[0] = *pos[1];
*pos[1] = c;
pos[0]++;
pos[1]--;
}
printf("reversed : %s\n",str);
return 0;
}

Related

Recreate strrchr() but getting extra characters at the end of string

A task I have is to recreate the function strrchr. I figured out a way to iterate backward from the input given and stopping at the character I need to stop at, but the string came out backwards obviously. I already had created a function to reverse a string so I used that to reverse it back to normal. It works, but somewhere in my while loop when stopping at the character, it adds extra characters. Please help! I don't understand why!
#include <stdio.h>
#include <string.h>
// #include <stddef.h>
int
main () {
char* my_strrchr(char* param_1, char param_2)
{
int i = strlen(param_1) - 1;
int q = 0;
char new[strlen(param_1)];
char *new_ptr = new;
while (i >= 0) {
new[q] = param_1[i];
printf("%c\n", new[q]);
if (param_1[i] == param_2) {
i = 0;
}
i--;
q++;
}
int size = strlen(new_ptr) - 1;
for (int i = 0, q = size; i < q; i++, q--) {
char temp = new_ptr[i];
new_ptr[i] = new_ptr[q];
new_ptr[q] = temp;
}
printf("%s", new_ptr);
return (char *)new_ptr;
}
char *phrase = "C Language is HARD.";
char c = 'g';
my_strrchr(phrase, c);
return 0;
}
You don't need to do anything fancy. Just walk the string from the beginning, updating a variable with the address of the character you're looking for every time it's found, and return it when you hit the end of the string (Unlike strchr(), where you return after the first match). That way you only need one pass through the string instead of the two times it takes if you first find the length and then go backwards.
#include <stdio.h>
#include <stdlib.h>
// Really should return a const char*. Silly standard.
char *my_strrchr(const char *s, int c) {
const char *pos = NULL;
while (*s) {
if ((unsigned char)*s == (unsigned char)c) pos = s;
s++;
}
if (c == 0) {
// If searching for '\0', return a pointer to the one
// at the end of the string
return (char *)s;
} else {
return (char *)pos;
}
}
int main(void){
const char *foo = "the quite wet duck quacks a lot";
puts(my_strrchr(foo, 'q'));
return 0;
}

how can I multiply strings in C like I do in python?

in python you can easily type:
str = "hi"
print(str * 10)
and the output would be hi printed 10 times. I'm currently learning how to code in C and I have to do this. Can someone teach me how I can do this kind of thing in C? Thanks in advance
Use for() loop:
Example:
#include <stdio.h>
int main() {
char* str = "hi";
for (int i = 0; i < 10; ++i) {
printf("%s", str);
}
}
And if you need to actually multiply the string (not just print n times) you can use the following mulstr(), just don't forget to test for NULL and to free():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
char* mulstr(char* str, size_t i) {
size_t len = strlen(str);
char* newstr = malloc(len * i + 1);
if (newstr) {
char* writer = newstr;
for (; i; --i) {
memcpy(writer, str, len);
writer += len;
}
*writer = 0;
} else {
perror("malloc");
}
return newstr;
}
int main() {
char* str = "hi";
char* newstr = mulstr(str, 10);
if (newstr) {
printf("%s", newstr);
free(newstr);
}
}
Using for-loop is the best way to implement this.
You can just create a customized print function which will do the same thing as python does. I am just giving a prototype here.
#include <stdio.h>
void print(char *string,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%s\n",string);
}
}
int main()
{
char *str="Hi";
print(str,2);
return 0;
}
Here second argument in the function n will tell you how many times you want to print the string.
The output will look like
Hi
Hi

Reverse a string recursively in C - using a pointer to string only

i'm trying to reverse a string using recursion and a single pointer to that string.
My idea is to traverse the string from both edges, raising the pointer and inserting '\0's at the end of the string. For example - given a string 'abcde\0' - replace "chars" before the middle of the string, and insert '\0' after -> recursive calls -> when "stop condition" is reached, original string should be like this - 'edc\0\0\0' - and half of chars stored as temp variable, in stack. When turning back and popping the stack, these chars should overwrite the '\0' in reverse order. This is the idea.
This is my code so far, but I can't get it work - please help me understand, what do I miss. I have a '\0' in the middle of string that I can't figure out how to rewrite it. (I guess this is the major problem)
Thanks in advance.
#include <stdio.h>
#include <string.h>
void rev_str(char* _str);
int main()
{
char str[]="abcde";
puts("Str before:");
puts(str);
rev_str(str);
puts("Str after");
puts(str);
return 0;
}
void rev_str(char* _str)
{
int len=strlen(_str);
char temp=*_str;
if(len>1)
{
*_str = _str[len-1];
_str[len-1]='\0';
rev_str(++_str);
}
_str[len-1]=temp;
}
I won't debug your code, however this might help you understand things better -
http://www.programmingsimplified.com/c-program-reverse-string
Examples taken from page -
C program to reverse a string using pointers
Now we will invert string using pointers or without using library function strrev.
#include<stdio.h>
int string_length(char*);
void reverse(char*);
main()
{
char string[100];
printf("Enter a string\n");
gets(string);
reverse(string);
printf("Reverse of entered string is \"%s\".\n", string);
return 0;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for (c = 0; c < length - 1; c++)
end++;
for (c = 0; c < length/2; c++)
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer + c) != '\0' )
c++;
return c;
}
C program to reverse a string using recursion
#include <stdio.h>
#include <string.h>
void reverse(char*, int, int);
int main()
{
char a[100];
gets(a);
reverse(a, 0, strlen(a)-1);
printf("%s\n",a);
return 0;
}
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverse(x, ++begin, --end);
}
rev_str(++_str);
This is the problem. You're modifying _str here so when you do _str[len-1]=temp at the end, you're writing to the wrong location. Change it to
rev_str(_str + 1);
Just change the code rev_str(++_str); into rev_str(_str+1);. The ++_str equal to _str += 1, it will change the pointer char *_str. But _str+1 will only initialize the formal param, and will not change the 'char *str'. I hope this can help you.

Is my use of pointers in this C program correct?

For example:
This is what I tried:
#include "stdafx.h"
#include <ctype.h>
char *mystrcat(char *s1p, char *s2p);
char main(void)
{
...........................
}
char *mystrcat(char *s1p, char *s2p)
{
printf("whatever = %s%s\n", s1p, s2p);
return 0;
}
How do I make this work with the 3rd pointer and have it store p1 and p2?
Replace: *mystrcat(string1, string2);
With: char *string3 = mystrcat(string1, string2);
Also if your teacher wants char*'s instead of
char string1[80];
char string2[80];
You could do
char *string1 = malloc(80*sizeof(char));
char *string2 = malloc(80*sizeof(char));
To concat your strings:
char *mystrcat(char *s1p,char *s2p) {
char *cat = malloc(2*80*sizeof(char));
int i = 0;
while(s1p[i]!='\o') {
cat[i] = s1p[i];
i++;
}
int j = 0;
while(s2p[j]!='\o') {
cat[i+j] = s2p[j];
j++;
}
return cat;
}
Bad coding habits aside (I've been doing C for a while, still haven't fixed some of em), there is one error I see: mystrcat(string1, string2). The return type is char, but the function itself has the pointer "in it" (hard to explain). So it should just be mystrcat(string1, string2)
It sounds like you want to write a function to concatenate strings. To do this you need to be able to visualize the strings in your head, the 2 input strings and the resultant string.
Here's an algorithm that should solve it:
Create a result string that has enough space for the total number of characters in the given input plus 1 for the terminating nul char.
Copy the bytes from the first string to the result.
Append the characters from the esconds string to the result
Append a nul character
return the result
Programming is the ability to see a problem, devise an algorithm and then implement in a programming language.
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
#include <ctype.h>
char *mystrcat(char*s1p, char*s2p); // Prototype
int main(void)
{
char *string1 = malloc(80*sizeof(char));
char *string2 = malloc(80*sizeof(char));
printf("Enter in string 1");
scanf("%s", string1);
printf("Enter in string 2");
scanf("%s", string2);
char *mystrcat((string1,string2));
return 0;
}
char *mystrcat(char *s1p,char *s2p)
{
char *cat = malloc(2*80*sizeof(char));
int i = 0;
while(s1p[i]!='\o') {
cat[i] = s1p[i];
i++;
}
int j = 0;
while(s2p[j]!='\o') {
cat[i+j] = s2p[j];
j++;
}
return cat;
}
this is the code i got so far with all of your lots help, i included everthing top to bottom, i am using MSVS 2012 and the reason i am posting this because i have an error on 'malloc' the error as fellows
3 IntelliSense: a value of type "void *" cannot be used to initialize an entity of type "char *" c:\Users\Sid\Documents\Visual Studio 2012\Projects\PORTFOLIO QUESTION 3\PORTFOLIO QUESTION 3\PORTFOLIO QUESTION 3.cpp 32

array iteration strstr in c

I was wondering if it's safe to do the following iteration to find the first occurrence of str within the array or if there is a better way. Thanks
#include <stdio.h>
#include <string.h>
const char * list[] = {"One","Two","Three","Four","Five"};
char *c(char * str) {
int i;
for (i = 0; i < 5; i++) {
if (strstr(str, list[i]) != NULL) return list[i];
}
return "Not Found";
}
int main() {
char str[] = "This is a simple string of hshhs wo a char";
printf("%s", c(str));
return 0;
}
Yes it's "safe" in the sense that the above code will work and there's no easy way to break it .
A little fix-up however would be more robust:
Return const char* from c() so that the caller cannot modify the resulting strings. All those strings are constant.
Instead of the magic number 5, which would become invalid if the array changed, use sizeof(list)/sizeof(list[0]) to compute the number of elements in the list.

Resources