Assign first character of a char array to another variable - c

I would like to grab a single character from a char array and move it into another character array. It is driving me crazy that i am having so much difficulties with something so simple.
My code is meant to reverse a string 2 values at a time. I have a string (ABCDEFGH) and i want to separate it into two strings (ACEG & BDFH). How would i go about doing this?
Currently, i have this:
char *hexrev(char str[]){
int i = 0;
char a[256];
char b[256];
int len = strlen(str);
for(i; i<len-1; i+=2)
{
printf("str[i] : %c\n", str[i]);
a[0] = str[i];
b[0] = str[i+1];
a[1] = '\0';
b[1] = '\0';
printf("A : %s\n", a);
printf("B : %s\n", b);
}
return str;
}
By changing sizeof(str) to strlen(str) and terminating a & b, I was able to get the code to work. Thank you!

You cannot use sizeof on an array inside a function. You must either use strlen() (once, preferrably) to compute the length, or pass it in as an extra argument.
Also you cannot legally print a and b as strings since you never ensure they're properly terminated.
Third, you only ever write to the first characters of a and b, so they will never grow longer than 1 character.
You should show a slightly more complete example, at least including the code that does the call to your function.

int i = 0, j = 0;
char a[256];
char b[256];
int len = strlen(str);
for(i; i<len-1; i+=2){
a[j] = str[i];
b[j++] = str[i+1];
}
a[j] = b[j] = '\0';
printf("A : %s\n", a);
printf("B : %s\n", b);
#include <stdio.h>
int main(void){
char str[] = "ABCDEFGHI";//In the case of odd-length
char a[256]={0};//letter of the index of odd numbered.(odd : 1 origin)
char b[256]={0};//for even
int i;
char *p[] = {a, b};
for(i = 0; str[i]; ++i){
*p[i & 1]++ = str[i];
}
printf("A : %s\n", a);//ACEGI
printf("B : %s\n", b);//BDFH
return 0;
}

Related

why strcat producing this error?

[Warning] passing argument 1 of 'strcat' makes pointer from integer without a cast THIS ERROR IS COMING WHEN I AM USING STRCAT WHAT SHOULD I DO , below is my code
#include <stdio.h>
#include <string.h>
void main() {
char a[20], b[256], p = NULL, f;
int i, j, n, k, c[20], t, x, l;
printf("enter the no of possible characters");
scanf("%d", &k);
printf("enter the possible characters in the dictionary");
printf("hi");
for (i = 0; i < k; i++) {
c[i] = (i);
a[i] = getchar();
}
for (i = 0; i < k; i++) {
printf("%d %s\n ", c[i], a[i]);
}
l = k;
printf("enter the string\n");
scanf("%s", &b);
n = strlen(b);
printf("%d", n);
for (i = 0; i < n; i++) {
strcat(p, b[i]);
}
getch();
}
This is because strcat takes null-terminated strings, not individual characters. You can work around this problem by null-terminating b at position n, and calling strcat once:
b[n] = '\0';
strcat(p, b);
This will append the initial n characters of b to p, all in one go. Of course, given that p does not have any characters in it, this is completely pointless: you might as well use strcpy. Of course, you need to declare p to be a character buffer large enough to hold all of b:
char a[20],b[256],p[256]={0},f;
// ^^^^^^^^^
b[n] = '\0';
strcpy(p, b);
Your variable definition is wrong.
char a[20],b[256],p=NULL,f;
does not define p as a pointer. It is a char variable with is not the expected type for the first argument of strcat().
You need to define p as a pointer to a string which has enough memory to hold the concatenated result.
That said,
strcat(p,b[i]);
is completely wrong, because b[i] is not a pointer to a string, either.

Write strcat() function with pointers

I am new with pointers on C and I am trying to write a function like strcat() but without using it. I developed the following function:
char cat(char *a, char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b);
char c[h]; //new string containing the 2 strings (a and b)
for(i;i<strlen(a);++i) {
c[i] = *(a+i); //now c contains a
}
int j = i;
for(j;j<strlen(b);++j) {
c[j] = *(b+cont); //now c contains a + b
cont++;
}
return c; // I return c
}
And this is how I call the function:
printf("\Concatenazione: %c", cat(A,B));
It is now working because the final result is a weird character. How could I fix the function? Here there's the full main.
char * strcat(char *dest, const char *src)
{
int i;
int j;
for (i = 0; dest[i] != '\0'; i++);
for (j = 0; src[j] != '\0'; j++) {
dest[i+j] = src[j];
}
dest[i+j] = '\0';
return dest;
}
From your implementation it appears that your version of strcat is not compatible with the standard one, because you are looking to allocate memory for the result, rather than expecting the caller to provide you with enough memory to fit the result of concatenation.
There are several issues with your code:
You need to return char*, not char
You need to allocate memory dynamically with malloc; you cannot return a locally allocated array.
You need to add 1 for the null terminator
You need to write the null terminator into the result
You can take both parameters as const char*
You can simplify your function by using pointers instead of indexes, but that part is optional.
Here is how you can do the fixes:
char *cat(const char *a, const char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b);
char *c = malloc(h+1);
// your implementation goes here
c[cont] = '\0';
return c;
}
You are returning a POINTER to the string, not the actual string itself. You need to change the return type to something like "char *" (or something equivalent). You also need to make sure to null terminate the string (append a '\0') for it to print correctly.
Taking my own advice (and also finding the other bug, which is the fact that the second for loop isn't looping over the correct indices), you end up with the following program:
#include <stdio.h>
char *cat(char *a, char *b) {
int i = 0, j = 0;
int cont = 0;
int h = strlen(a) + strlen(b) + 1;
char *result = (char*)malloc(h * sizeof(char));
for(i = 0; i < strlen(a); i++) {
result[i] = a[i];
}
for(j = i; j < strlen(b)+ strlen(a); j++) {
result[j] = b[cont++];
}
// append null character
result[h - 1] = '\0';
return result;
}
int main() {
const char *firstString = "Test First String. ";
const char *secondString = "Another String Here.";
char *combined = cat(firstString, secondString);
printf("%s", combined);
free(combined);
return 0;
}
c is a local variable. It only exists inside the function cat. You should use malloc.
instead of
char c[h];
use
char *c = malloc(h);
Also, you should add the null byte at the end. Remember, the strings in C are null-ended.
h = strlen(a) + strlen(b) + 1;
and at the end:
c[h - 1] = '\0';
The signature of cat should be char *cat(char *a, char *b);
You will get an error of
expected constant expression
for the code line char c[h];. Instead you should be using malloc to allocate any dynamic memory at run-time like::
char* c ;
c = malloc( h + 1 ) ; // +1 for the terminating null char
// do stuff
free( c ) ;
Your corrected code::
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include <stdlib.h>
char* cat(char *a, char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b), j;
char *c;
c = malloc( h+1 ) ;
for(i;i<strlen(a);++i) {
c[i] = *(a+i);
}
j = 0 ;
for(j;j<strlen(b);++j) {
c[i] = *(b+cont);
i++ ;
cont++;
}
c[i] = 0 ;
return c;
}
int main() {
char A[1000],B[1000];
char * a ;
printf("Inserisci la stringa 1: \n");
gets(A);
printf("Inserisci la stringa 2: \n");
gets(B);
a = cat(A,B) ;
printf("\nConcatenazione: %s", a);
free(a) ;
getch();
return 0;
}

Reverse char array with pointer in C

I want to reverse a char array using pointers, but all I get when I printf the pointer is null. I don't know what I'm doing wrong or how to fix it. So how can I reverse the string in a similar way?
#include <stdio.h>
void reverse(char *cstr);
int main()
{
char a[100];
char *p = a;
printf("geef een string "); // ask user to write a word
scanf("%s", &a);
reverse(p);
printf("%s", *p);
}
void reverse(char *p)
{
int i = 0;
char temp;
int lengte;
for(i = 0; *(p+i) != '\0'; i++)
{
lengte++; // length of char array without the '\0'
}
for(i = 0; i < lengte; i++)
{
temp = p[i]; // something goes wrong here but I don't know what
p[i] = p[lengte-i];
p[lengte-i] = tem;
}
}
Something goes wrong at the
p[i] = p[lengte-i];
p[lengte-i] = tem;
part. What do I need to change it to?
Two adjustments:
replace
printf("%s", *p);
with
printf("%s", p);
because printf is expecting a pointer, not a dereferenced pointer,
and
for(i = 0; i < lengte; i++)
with
for(i = 0; i < lengte--; i++)
because your counting of the length in the loop before that one ends up with one char too many. Hence the \0 is placed at the beginning of the string.
$ gcc test.c && ./a.out
geef een string 1234
4231$

C: Garbage characters in Console output

I am learning about C pointers by creating various simple functions. I have just created a function to reverse a char array. It works, but after the output it also displays a bunch of garbage chars (see screenshot below).
Here's my code:
void reverseString();
int main()
{
reverseString();
system("PAUSE");
return 0;
}
void reverseString()
{
char string1[20], string2[20];
char *ptr1, *ptr2;
ptr1 = &string1[0];
ptr2 = &string2[0];
printf("Enter string: \n");
scanf("%s", string1);
int len1 = strlen(string1);
int i;
for (i = 0; i < len1; i++)
{
ptr2[i] = ptr1[len1 - i - 1];
}
printf("%s\n", string2);
}
How can I get rid of the garbage chars? Is there something wrong with my code or did I just nto account for something or what?
You forgot to nul-terminate the new string:
int i;
for (i = 0; i < len1; i++)
{
ptr2[i] = ptr1[len1 - i - 1];
}
// Add this
ptr2[i] = '\0';
When you print a char*, it will keep reading until it finds that nul character. But since you left it out, it kept going and going...

Something is wrong with this C code to reverse string, but I dont know what ? please help

I am beginnner to programming. I wrote this little program to reverse a string. But if I try to reverse a string which is less than 5 characters long then it gives wrong output. I cant seem to find whats wrong.
#include<stdio.h>
#include<string.h>
int main()
{
char test[50];
char rtest[50];
int i, j=0;
printf("Enter string : ");
scanf("%s", test);
int max = strlen(test) - 1;
for ( i = max; i>=0; i--)
{
rtest[j] = test[i];
j++;
}
printf("Reversal is : %s\n", rtest);
return 0;
}
You are not terminating the reversed string with a 0. (all strings in C are 0-terminated)
In this case, the printf will (likely, depending on the unitialized contents of the rtest array) create a buffer overflow.
Add a rtest[max+1]=0; after the for loop and everything should be fine.
Otherwise you can declare char rtest[50] = {0} (this will initialize the whole array with 0s).
rtest is unitialized.
You should add rtest[j] = '\0'; after the for loop to say where the string ends
void reverse(char* str)
{
int len = strlen(str);
for (int i = 0; i < len / 2; ++i) {
char tmp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = tmp;
}
}

Resources