I have written below program to reverse the string, but it is not printed after reversal.
What could be the issue?
#include<stdio.h>
#include<string.h>
main()
{
char p[] = "krishna";
strrv(p);
printf("%s", p); // -----> nothing prints here
}
void strrv(char p[])
{
int l = strlen(p);
int i=0;
char tmp;
while(i<l)
{
tmp = p[i];
p[i] = p[l];
p[l] = tmp;
i++;
l--;
}
}
On the first loop iteration p[l] will refer to the terminating \0 of p which is then assigned to p[0] and that in turn that makes p an empty string. The fix is to initialize l to strlen(p) - 1 instead of strlen(p):
#include <stdio.h>
#include <string.h>
void strrv(char p[]) {
for(int i = 0, l = strlen(p) - 1; i < l; i++, l--) {
char tmp = p[i];
p[i] = p[l];
p[l] = tmp;
}
}
int main() {
char p[] = "krishna";
strrv(p);
printf("%s", p);
return 0;
}
Related
I need to split the string of n size and append in an array.
For example:
input:
abcdefghi
4
output:
[abcd,bcde,cdef,defg,efgh,fghi]
My code giving wrong answer:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "abcdefghi";
char result[100];
for(int i=0;i<strlen(str);i++){
strncat(result, str, str[i]+4);
}
printf("result: %s\n ", result);
}
My output:
abcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgi
What mistake have I made??
Would you please try the following:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "abcdefghi";
char result[100];
int n = 4;
int i, j;
char *p = result; // pointer to the string to write the result
*p++ = '['; // left bracket
for (i = 0; i < strlen(str) - n + 1; i++) { // scan over "str"
for (j = i; j < i + n; j++) { // each substrings
*p++ = str[j]; // write the character
}
*p++ = i == strlen(str) - n ? ']' : ','; // write right bracket or a comma
}
*p++ = '\0'; // terminate the string with a null character
printf("result: %s\n", result); // show the result
return 0;
}
Output:
result: [abcd,bcde,cdef,defg,efgh,fghi]
Might this work for you?
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "abcdefghijklmno";
char result[100][100];
int nSplit = 4; //Split size
int nLength = strlen (str); //Lenth of the string
int nTotalString = nLength - nSplit; //total possibilities
int nStrCount = 0;
for (int i = 0; i <= nTotalString ; i ++)
{
for (int j = 0; j < nSplit; j++)
result[nStrCount][j] = str[i + j];
nStrCount++;
}
//print array
printf ("result:[");
for (int k = 0; k < nStrCount; k++)
printf ("\"%s\" ", result[k]);
printf ("]");
return 0;
}
Hi I am pretty new to C and was wondering how to return an entire array. For example I have this function here.
char* foo(int x)
{
char *num = (char*)malloc(x*sizeof(int));
num[0] = '1';
num[1] = '2';
num[2] = '3';
num[3] = '4';
return num;
}
I realized that when I return num it only returns the first index of num. But is there any way to return the whole array, 1234? Any help will be greatly appreciated!
Since the foo() function returns a pointer, you can see that all values are printed when you use the %s format specifier. The display() function prints the data in the memory area pointed to by the pointer as characters.
#include <stdio.h>
#include <stdlib.h>
char* foo(int x)
{
char* num = (char*) malloc((x + 1) * sizeof(char));
for(size_t i = 0 ; i < x ; ++i)
num[i] = i + 1 + '0';
num[x] = '\0';
return num;
}
void display(char *array, size_t size)
{
for(size_t i = 0 ; i < size && array[i] != '\0' ; ++i)
printf("array[%ld]: %c\n", i, array[i]);
}
int main()
{
const size_t size = 4;
char *result = foo(size);
printf("%s\n", result);
display(result, size);
return 0;
}
Output:
1234
array[0]: 1
array[1]: 2
array[2]: 3
array[3]: 4
See if you are new to C, then learn it first do some googling and research. If you don't find anything then read some theory of a similar topic for examples (How to return an array in C?). After that some error is happening in your code then you can ask it on stackoverflow.
By the way your should be like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *foo(int x); // fix prototype errors
char *foo(int x)
{
char *num = (char *)calloc(x + 1, sizeof(char)); // we added +1 to append the null terminating character in `num`
for (size_t i = 0; i < x; i++)
num[i] = (char)(i + 48);
return num;
}
/* #returns no. of character written on stdout */
int print_foo(const char *num); // fix prototype errors
int print_foo(const char *num)
{
if (num)
{
size_t z = 0;
for (size_t i = 0; i < num[i] != '\0'; i++)
z += fprintf(stdout, "num[%lu] = %c\n", i, num[i]);
return z;
}
return -1;
}
int main(void)
{
char *num = foo(10);
print_foo((const char *)num);
free(num); // free any heap allocated resources before exiting the application
return 0;
}
I have written some code on to find the number of times the characters repeated in the string.Considered 2 pointers and allocated memory dynamically, then input the string into one of the pointers.Then copying the characters without redundancies into the another pointer and finally comparing it, incrementing the count and printing to the screen.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void string_cpy(char *from, char *to);
int len(char *p);
int main()
{
char *name, *copy, *hold;
int i, j, lent, count = 0, length;
name = (char *)calloc(25, sizeof(char));
copy = (char *)calloc(25, sizeof(char));
printf("Give a string:");
scanf("%s", name);
puts("");
string_cpy(name, copy);
hold = name;
lent = len(copy); //l=4
length = len(name); //lenght = 5
printf("Characters and their corresponding frequencies\n");
for (i = 0; i < lent; ++i)
{
for (j = 0; j < length;)
{
if (*(copy) == *(name))
{
++count;
++name;
++j;
}
else
{
++j;
++name;
}
}
name = hold;
printf("%c-%d\n", *(copy), count);
count = 0;
++copy;
}
free(name);
free(copy);
return 0;
}
void string_cpy(char *from, char *to)
{
int i, j, k, l, ex;
char key;
l = len(from); //l=5
char *t = to;
for (i = 0, j = 0; i < l; ++i)
{
key = *(from + i);
ex = 0;
for (k = 0; k < i; ++k)
{
if (*(to + k) == key)
{
ex = 1;
}
}
if (!ex)
{ //if(ex==0)
strcpy((to + j), (from + i));
++j;
}
}
}
int len(char *p)
{
int leng = 0;
while (*p != '\0')
{
++leng;
++p;
}
return leng;
}
when I try to free() up both the pointers or the '''char *copy''' it throws me an error
->malloc: *** error for object 0x120e06884: pointer being freed was not allocated
->malloc: *** set a breakpoint in malloc_error_break to debug
This was done on my Mac OS
You change the value of the calloced pointer. It does not reference anymore the allocated memory block.
++copy;
I've got a problem with some chars and i can't figure out how to solve it. It is given a sequence of strings and another string. And I have to count the number of appearances of the string in the sequence of strings. I did the program below but it doesn't work.
main.cpp
#include "tipulbool.h"
char sir1[25], sir2;
int n, i, k;
int main (){
cin>>n;
for(i = 1; i <= n; i++)
cin>>sir1[i];
cin>>sir2;
for(i = 1; i <= n; i++)
k += secventa(sir1[i], sir2);
cout<<k;
return 0;
}
tipulbool.h
#include <iostream>
#include <string.h>
using namespace std;
int secventa (char sir1[], char sir2);
tipulbool.cpp
#include "tipulbool.h"
int secventa (char sir1[], char sir2){
int contor;
char *p;
p = strstr(sir1[], sir2);
if(p)
contor++;
while(p){
p = strstr(p + 1, sir2);
if(p)
contor++;
}
return contor;
}
try this:
int countOfChars(char sir1[], char sir2)
{
int count = 0;
char* p = sir1;
while (*p)
{
if (p == sir2)
{
++count;
}
++p;
}
return count;
}
this code:
#include "tipulbool.h"
int secventa (char sir1[], char sir2){
int contor;
char *p;
p = strstr(sir1[], sir2);
if(p)
contor++;
while(p){
p = strstr(p + 1, sir2);
if(p)
contor++;
}
return contor;
}
gets lost in it self.
suggest:
#include "tipulbool.h"
int secventa (char sir1[], char sir2){
int contor = 0;
char *p = str1;
while(NULL != (p = strchr(p, str2) ) )
{
contor++;
p++;
}
return contor;
}
However, note that
1) I used `strchr()` rather than `strstr()`
because `str2` is a single char, not a string
2) I removed the repetitive code
3) `str1` MUST be a NULL terminated string, which in the posted code is not the case.
regarding this code:
#include "tipulbool.h"
char sir1[25], sir2;
int n, i, k;
int main (){
cin>>n;
for(i = 1; i <= n; i++)
cin>>sir1[i];
cin>>sir2;
for(i = 1; i <= n; i++)
k += secventa(sir1[i], sir2);
cout<<k;
return 0;
}
in C++, an array offset starts with 0 and continues to (length of array -1)
variables that are only used in a single function should (in general) be defined as local/auto variables within that function.
suggest using code similar to the following:
#include "tipulbool.h"
int main ( void )
{
char sir2;
int n; // will contain number of char in str1
int i; // loop counter
int k = 0; // will contain number of occurrence of str2 in str1
// get count of chars in first string
cin >> n;
// allocate room for first string (using C string)
// +1 to allow for NUL terminator byte
char *sir1 = new char[n+1];
// initialize first string
memset( sir1, 0x00, n+1 );
// input first string
for(i = 0; i < n; i++)
cin >> sir1[i];
// input target char
cin >> sir2;
// get count of occurances of str2 in str1
k = secventa(sir1, sir2);
cout << k << endl;
delete [] str1;
return 0;
}
Since this is C++, you might want to look at vector or string
to simplify the written part of the code even further
i have written a program to reverse a string.. But it is not working.. It is printing the same string which is scanned.. What is the problem with the code?
#include <stdio.h>
#include <stdlib.h>
char *strrev(char *s)
{
char *temp = s;
char *result = s;
char t;
int l = 0, i;
while (*temp) {
l++;
temp++;
}
temp--;
for (i = 0; i < l; i++) {
t = *temp;
*temp = *s;
*s = t;
s++;
temp--;
}
return result;
}
int main()
{
char *str;
str = malloc(50);
printf("Enter a string: ");
scanf("%s", str);
printf("%s\n\n", strrev(str));
return 0;
}
for (i = 0; i < l; i++)
You're walking through the entire string, so you're reversing it twice - it won't be reversed after all. Walk only halfways:
for (i = 0; i < l / 2; i++)
Also, try using int len = strlen() instead of the while-not-end-of-string loop, if you're permitted to do so.
You swap the string's content twice.
Use the following code ..
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
char *strrev(char *s)
{
char *temp = s;
char *result = s;
char t;
while (*temp)
temp++;
while (--temp != s)
{
t = *temp;
*temp = *s;
*s++ = t;
}
return result;
}
int main()
{
char *str;
str = (char*)malloc(50);
printf("Enter a string: ");
scanf("%s", str);
printf("%s\n\n", strrev(str));
return 0;
}
The logic is to swap characters from start upto first half with the characters from last of second half, i.e, upto len/2. Just modify your for loop as below & it will work fine for you
for (i = 0; i < l/2; i++) {
you can use this simple code
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int str_len (char *str)
{
char *ptr = str;
while (*str)
str++;
return str - ptr;
}
int main ()
{
char *str;
int length;
str = (char*)malloc(50);
printf("Enter a string: ");
scanf("%s", str);
length = str_len(str) - 1;
for (int i = length ; i >= 0 ; i--)
printf ("%c", str[i]);
return 0;
}
you can use this code to reverse the string
#include<stdio.h>
#include<string.h>
int main()
{
int n,i;
char str2[100],str1[100];
printf("enter teh string 1\n");
gets(str1);
n = strlen(str1);
for(i=0;i<n;i++)
{
str2[n-1-i]=str1[i];
}
printf("%s\n",str2);
}
Actually you are reversing the string twice...so after come to middle of the string, you should terminate the loop that is your loop should be run for half of the string length that is l/2 (in this case). so your loop should be like
for(i = 0; i < i / 2; i++)
swapping the string content twice..
swapping it once will help..
for (i = 0; i < l/2; i++)