I'm trying to write a simple C function to copy the contents of one char array to another using pointer arithmetic. I can't seem to get it working, can you tell me where I'm going wrong?
#include <stdio.h>
#include <stdlib.h>
void copystr(char *, const char *);
int main()
{
char hello[6] = "hello";
const char world[6] = "world";
copystr(&hello, &world);
return 0;
}
void copystr(char *str1, const char *str2)
{
*str1 = *str2; //copy value of *str2 into *str1
printf("%s %s", *str1, *str2); //print "world" twice
}
Help appreciated, thanks.
EDIT:
Here is the working code:
#include <stdio.h>
#include <stdlib.h>
void copystr(char *, const char *);
int main()
{
char hello[6] = "hello";
const char world[6] = "world";
copystr(hello, world);
printf("%s %s", hello, world);
return 0;
}
void copystr(char *str1, const char *str2)
{
/*copy value of *str2 into *str1 character by character*/
while(*str2)
{
*str1 = *str2;
str1++;
str2++;
}
}
You are only copying the first character of the string.
void copystring(char* str1, const char* str2)
{
while(*str2)
{
*str1 = *str2; //copy value of *str2 into *str1
str1++;
str2++;
}
}
and then in main, after calling copystring
printf("%s %s", hello, world); //print "world" twice
But please don't do this! Use strncpy in real life, if working with plain C strings.
Related
I'm trying to use strcpy() with pointers to strings and after a successful compilation when I run it it gives error. I don't know why this is happening.
int main()
{
char *s1="abcd";
char *s2="efgh";
strcpy(s2,s1);
printf("%s\n", s1);
printf("%s\n",s2);
getch();
}
These are string literals, you can't modify them because they're stored in read-only memory.
If you want to change this so you can modify them, use char s[]. This will store the strings on the stack:
char s1[] = "abcd";
char s2[] = "efgh";
If you want pointers to these, simply create pointers:
char *p1 = s1;
char *p2 = s2;
or you can create them with compound literals from C99:
char *p1 = (char []){"abcd"};
char *p2 = (char []){"efgh"};
A full program that puts the strings on the stack:
int main(void)
{
char s1[] = "abcd";
char s2[] = "efgh";
strcpy(s2, s1);
printf("%s\n", s1);
printf("%s\n", s2);
getchar();
}
Output:
abcd
abcd
You are trying to copy all content from first pointer string to second pointer string then I like to suggest you to use malloc
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char *s1 ="abcd";
char *s2 ="efgh";
s2 = (char *) malloc(1 + strlen(s1));
strcpy(s2, s1);
printf("%s\n", s1);
printf("%s\n", s2);
return 0;
}
output -:abcd
abcd
hope this will fulfill your question
I am very new to programming with C and I can't find a way to add to this program in order to spell "Hello, World!" without deleting any lines of code here.
#include <stdio.h>
#include <string.h>
void modify_1(char *c);
void modify_2(char *c);
int main()
{
char str1[10];
char str2[15];
printf("%s, %s!\n", str1, str2);
}
void modify_1(char *c)
{
char *a_string = "hello";
}
void modify_2(char *c)
{
char *a_string = "world";
}
Consider the following code (see here in onlineGDB):
#include <stdio.h>
#include <string.h>
void modify_1(char *c);
void modify_2(char *c);
int main(void)
{
char str1[10];
char str2[15];
modify_1(str1);
modify_2(str2);
printf("%s, %s!\n", str1, str2);
}
void modify_1(char *c)
{
strcpy(c, "hello");
}
void modify_2(char *c)
{
strcpy(c, "world");
}
There are a few changes:
You actually call modify_1 and modify_2 (otherwise, why would they affect anything?)
Within the functions, you use strcpy to copy the content of the literal to the address.
I can't find a way to add to this program in order to spell "Hello, World!"
without deleting any lines of code here.
Given that you cannot delete any lines, you need only add 2-lines of code to each of your modify_1 and modify_2 functions to (1) copy the string-literals to your array, and then (2) change the first characters from lowercase to uppercase, and then just call modify_1 and modify_2 before you print.
For example:
void modify_1 (char *c)
{
char *a_string = "hello";
strcpy (c, a_string); /* copy a_string to your array */
c[0] = c[0] + 'A' - 'a'; /* change 1st character to uppercase */
}
void modify_2 (char *c)
{
char *a_string = "world";
strcpy (c, a_string); /* same thing */
c[0] = c[0] + 'A' - 'a';
}
After making the changes, you simply call the functions before your print statement in main(), e.g.
int main()
{
char str1[10];
char str2[15];
modify_1 (str1);
modify_2 (str2);
printf("%s, %s!\n", str1, str2);
}
Example Use/Output
$ ./bin/modify_12
Hello, World!
See ASCII Table and Description to understand how the conversion from lowercase to uppercase takes place.
This is probably not what is intended by the person that gave you the assignment but the simplest solution is to add two lines in main and leave the rest unchanged (and unused :-)
int main()
{
char str1[10];
char str2[15];
strcpy(str1, "Hello"); // Add this line
strcpy(str2, "World"); // Add this line
printf("%s, %s!\n", str1, str2);
}
I want to do in C, what can be achieved in Java as follows
String str = "hello";
System.out.println(str + 'a');
I have written the following.
1. It doesn't work
2. Is there an easier way to do this in C, something that can be achieved in java in a single line.
#include <stdio.h>
char* charcat(char str[], char c);
int main(void)
{
char str[] = "hello";
printf("%s\n",charcat(str,'a'));
}
char* charcat(char str[], char c)
{
char newstr[] = {c,'\0'};
char temp[20];
strcpy(temp,str);
strcat(temp,newstr);
return temp;
}
EDIT :
I have edited based on ameyCU's response.
char* charcat(char str[], char c);
int main(void)
{
char str[] = "hello";
printf("%s\n",charcat(str,'a'));
}
char* charcat(char str[], char c)
{
char* temp;
char newstr[] = {c,'\0'};
temp = malloc((strlen(str) + 1)* sizeof(char));
strcpy(temp,str);
return strcat(temp,newstr);
}
EDIT 2:
char* charcat(char str[], char c);
int main(void)
{
char str[] = "hello";
char temp[20];
strcpy(temp,str);
printf("%s\n",charcat(temp,'a'));
}
char* charcat(char str[], char c)
{
char newstr[] = {c,'\0'};
return strcat(str,newstr);
}
I think what you were trying to do was this:
char* charcat(char str[], char c)
{
char newstr[] = {c,'\0'};
char *temp=(char *)malloc((strlen(str)+1+1)*sizeof(char));
strcpy(temp,str);
strcat(temp,newstr);
return temp;
}
make sure you free() the pointer.
You can use strcat() function
char str1[20]="hello";
strcat(str1,"c");
printf("%s",str1);
Problem is that you return a local variable.
return temp;
temp is local variable and its scope is just inside the function it is declared.
After concatenation -strcat(temp,newstr);
You can do this -
strcpy(str,temp);
return str;
But this will also change the contents of original array.
EDIT
To keep original array intact assign a pointer to string in function and return the pointer .
And also to use functions like strcpy and strcat you need to include string.h header.
This uses snprintf() to get the required length for the target string. Memory is allocated and then snprintf() creates the target string.
#include<stdio.h>
#include<stdlib.h>
char* charcat(char str[], char c);
int main ( ) {
char str[] = "hello";
char *output = NULL;
printf ( "str-> %s\n\n", str);
if ( ( output = charcat ( str, 'a'))) {//successful return of pointer
printf ( "output-> %s\n", output);
free ( output);//release memory
}
return 0;
}
char* charcat(char str[], char c)
{
char *temp = NULL;
int length = 0;
length = snprintf ( NULL, 0, "%s%c", str, c);//get required length
if ( ( temp = malloc ( length + 1))) {//allocate plus one for '\0'
snprintf ( temp, length + 1, "%s%c", str, c);//malloc succeeds make target
}
return temp;
}
It is always better to use strncat() instead of strcat to avoid buffer overflows.
#include <cstdio>
#include <cstring>
int main ()
{
char str[20] = "hello";
strncat (str, "a", sizeof(str) - strlen(str) - 1);
printf("%s",str);
return 0;
}
Output:
helloa
RUN SUCCESSFUL (total time: 49ms)
Something like Java in a single line
// String str = "hello";
// System.out.println(str + 'a');
const char *str = "hello";
printf("%s%c\n", str, 'a');
Or is one wants to print a concatenated string, we need to do memory management.
char *charcatconst char *src, int ch) {
size_t len = strlen(src);
char *s = memcpy(malloc(len+2), src, len); // Out-of-memory check omitted.
s[len] = ch;
s[len+1] = '\0';
return s;
}
// simple usage, but a memory leak
puts(charcat("hello", 'a'));
// Better to free memory explicitly
char *s = charcat("hello", 'a');
puts(s);
free(s);
2 strings are given, second word will be append to first one and 3rd variable will store this. For example;
char *str1 = "abc";
char *str2 = "def";
char *str3 = "abcdef"; //should be
Here is my code, I get runtime error:
#include <stdio.h>
#include <malloc.h>
void append(char *str1, char *str2, char *str3, int size1, int size2)
{
int i=0;
str3 = (char*) malloc(size1+size2+1);
str3 = str1;
while (str2[i] != '\0') {
str3[i+size1] = str2[i];
i++;
}
str3[size1+size2] = '\0';
}
int main()
{
char *str1 = "abc";
char *str2 = "def";
char *str3;
append(str1, str2, str3, 3, 3);
return 0;
}
str3 = (char*) malloc(size1+size2+1);
str3 = str1;
Here's your problem. Doing this replaces the pointer to the correct amount of space from malloc to the pointer where str1 is contained. Keeping with your loop design, change this to:
str3 = malloc(size1+size2+1);
for (int j = 0; str1[j] != '\0'; j++)
str3[j] = str1[j];
Also, see this question/answer about casting the result of malloc in C:
Do I cast the result of malloc?
There is another issue with the code. You pass pointer by value. So any malloc inside a function will do only local changes. After function ends your pointer will still point to the old value. You should pass a pointer to pointer if you want to change it. See an example:
#include <stdio.h>
char *c = "Second";
void assign(char *s) { s = c; }
int main()
{
char *str = "First";
assign(str);
printf("String after assign: %s\n", str);
return 0;
}
After running the program you will see 'First' in you console. The correct code is:
#include <stdio.h>
char *c = "Second";
void assign(char **s) { *s = c; }
int main()
{
char *str = "First";
assign(&str);
printf("String after assign: %s\n", str);
return 0;
}
#include <stdio.h>
#include <stdlib.h> //to standard
#include <string.h>
char *append(const char *str1, const char *str2, int size1, int size2){
//parameter char *str3 is local variable.
//It is not possible to change the pointer of the original.
//str3 = str1;//<<-- memory leak
//str3[i+size1] = str2[i];//<<-- write to after str1(can't write!)
char *str3 = (char*) malloc(size1+size2+1);
memcpy(str3, str1, size1);//copy to alloc'd memory.
memcpy(str3 + size1, str2, size2);//copy to after str1
str3[size1+size2] = '\0';
return str3;
}
int main(){
char *str1 = "abc";
char *str2 = "def";
char *str3;
str3 = append(str1, str2, 3, 3);
printf("%s\n", str3);
return 0;
}
I'm trying to run function which will return two strings by passing a pointer to them:
#include <stdio.h>
void gen_str(char *str1, char *str2){
char *s1 = "abcd";
char *s2 = "defg";
str1= strdup(s1);
str2= strdup(s2);
printf("\n\r str1 %s str2 %s\n\r", str1, str2);
}
int main(void){
char *s1, *s2;
gen_str(s1, s2);
printf("\n\r s1 %s s2 %s\n\r", s1, s2);
return 0;
}
where output is:
str1 abcd str2 defg
s1 8, s2 8,
Can someone tell me, what I'm doing wrong? I thought that strdup() will alloc memory for my new strings, and return pointers filled with strings. But actual behavior is different. So I'm asking for help.
You need your function to modify the pointers s1 and s2, so you need to pass their addresses, so that the function can modify the originals, not a copy.
void gen_str(char **str1, char **str2){
char *s1 = "abcd";
char *s2 = "defg";
*str1= strdup(s1);
*str2= strdup(s2);
printf("\n\r str1 %s str2 %s\n\r", *str1, *str2);
}
int main(void){
char *s1, *s2;
gen_str(&s1, &s2);
printf("\n\r s1 %s s2 %s\n\r", s1, s2);
return 0;
}
Note also that you need to free these strings at some point, otherwise you have a memory leak.
You got your pointers confused. The basic type for a C string is already char*, and now you want a pointer to that, i.e. a char**:
void fill_me(char ** ps)
{
const char * t = "hello";
*ps = strdup(t);
}
/* elsewhere */
char * s;
fill_me(&s);
Moral: If you want a function to modify an argument passed by the caller, the caller needs to take the address-of (&) something at some point.
You're only changing the pointer inside the function. To change it outside the function, you'll need to pass the function the address of the two strings, like this:
#include <stdio.h>
void gen_str(char **str1, char **str2){
char *s1 = "abcd";
char *s2 = "defg";
*str1= strdup(s1);
*str2= strdup(s2);
printf("\n\r str1 %s str2 %s\n\r", *str1, *str2);
}
int main(void){
char *s1, *s2;
gen_str(&s1, &s2);
printf("\n\r s1 %s s2 %s\n\r", s1, s2);
return 0;
}
You can's use the value of a variable before you've initialized it!
char *s1, *s2;
gen_str(s1, s2);
The first line doesn't assign any particular values to s1 and s2. But then you pass them to gen_str. To have another function fill in the value of a variable, pass a pointer to that variable to the function, not its value.
#include <stdio.h>
#include <string.h>
void gen_str(char **str1, char **str2){
const char *s1 = "abcd";
const char *s2 = "defg";
*str1 = strdup(s1);
*str2 = strdup(s2);
printf("\n str1 %s str2 %s\n", *str1, *str2);
}
int main(void){
char *s1, *s2;
gen_str(&s1, &s2);
printf("\n s1 %s s2 %s\n", s1, s2);
free(s1);
free(s2);
return 0;
}