What to add to this Hello World code in C? - c

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);
}

Related

Use of strcpy() in pointers to string in C

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

C -swap 2 chars recursively with only one pointer

I need to write a function:
void swap (char * s1, char * s2);
The function will replace the contents of both strings 1s and 2s.
Constraints:
In the function, there is no use of [] anywhere, but performance by working with pointers, in addition, trips must be made with the voters, meaning that they will actually move to another cell as needed, and will not remain in the same location all the time.
• No loops in the function, that is, work in recursion.
I did the function with pointer to pointer str** but must change it to only one pointer str and recursively. How can I change it?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str1="abc",*str2="xyz",*pRev;
swap(&str1, &str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}
//need *str NOT **str
void swap(char **str1, char **str2);
char * RevWords (char * str, int size);
void swap(char **str1, char **str2)
{
char *temp = *str1_ptr;
*str1_ptr = *str2_ptr;
*str2_ptr = temp;
}
after swap method:
str2="abc", str1="xyz"
Well this is clearly not an ideal solution but gives you something to work with.
However this will only work (as mentioned above) when you have the same length of strings (or yes, you'll have to allocate memory + you'd need to know the length of your strings). But otherwise I think this may answer your question.
This is working with recursion and depends on the fact that both strings are the same length and containing a zero character at the end of each one.
#include <stdio.h>
#include <stdlib.h>
void swap(char* str1, char* str2)
{
// if both of them are zero characters then stop
if (*str1 == '\0' && *str2 == '\0')
return;
// else swap the contents of the pointers
else
{
char tmp = *str1;
*str1 = *str2;
*str2 = tmp;
// advance both pointer and swap them too if thye are not '\0'
swap(++str1, ++str2);
}
}
int main()
{
char str1[] = "abc\0\0\0"; // padded with zeros to be the same length as str2
char str2[] = "xyz123"; // the last '\0' is automatically added
swap(str1, str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}

C - Copy contents of one char array to another using pointers

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.

whats wrong with my code(copying string using pointers?)?

//a function that copies one string to another
copy(char *,char*);
main()
{
char one[20],two[20];
printf("enter two sentences \n\n");
gets(one);//first string
gets(two);//second string
copy(one,two);
printf("%s",two);
}
copy(char *s1,char *s2)
{
while(*s1!='\0')
{
s2=s1;
s1++;
s2++;
}
s2='\0';
}
what wrong with the above program ? why the string 'one' is not getting copied to string 'two'?please explain with the help of pointer
It's because this:
s2 = s1;
changes the pointer s2 so that it points to the content of s1.
What you want to do is copy the content:
*s2 = *s1;
A decent compiler should also have given you a warning on this line:
s2 = '\0';
since you're assigning a char to a char *. It should be:
*s2 = '\0';
Enacting those changes, the function would then be (including using some, IMNSHO, better variable names):
void copy (char *from, char *to) {
while (*from != '\0') {
*to = *from;
from++;
to++;
}
*to = '\0';
}
Or, once your brain has been warped by several decades of C use like mine :-)
void copy (char *from, char *to) {
while (*to++ = *from++);
}
#include <stdio.h>
#include <string.h> /* for strchr */
void copy(const char *, char*); /* use void to return nothing */
int main(void) /* main() is not valid */
{
char one[20], two[20];
char *ptr;
printf("enter two sentences \n\n");
/* gets is deprecated, use fgets in order to avoid overflows */
fgets(one, sizeof one, stdin);
/* fgets leaves a trailing newline, remove it */
if ((ptr = strchr(one, '\n'))) *ptr = '\0';
fgets(two, sizeof two, stdin); /* why? is gonna be replaced by one */
copy(one, two);
printf("%s\n", two);
return 0;
}
void copy(const char *s1, char *s2) /* s1 is not modified, use const */
{
while(*s1 != '\0')
{
*s2 = *s1; /* Don't assign addresses, assign values */
s1++;
s2++;
}
*s2 = '\0';
}

How do I concatenate two strings in C?

How do I add two strings?
I tried name = "derp" + "herp";, but I got an error:
Expression must have integral or enum type
C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.
Use strcat to concatenate two strings. You could use the following function to do it:
#include <stdlib.h>
#include <string.h>
char* concat(const char *s1, const char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;
}
This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.
Call the function like this:
char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string
If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.
char* concat(const char *s1, const char *s2)
{
const size_t len1 = strlen(s1);
const size_t len2 = strlen(s2);
char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
memcpy(result, s1, len1);
memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
return result;
}
If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.
#include <stdio.h>
int main(){
char name[] = "derp" "herp";
printf("\"%s\"\n", name);//"derpherp"
return 0;
}
David Heffernan explained the issue in his answer, and I wrote the improved code. See below.
A generic function
We can write a useful variadic function to concatenate any number of strings:
#include <stdlib.h> // calloc
#include <stdarg.h> // va_*
#include <string.h> // strlen, strcpy
char* concat(int count, ...)
{
va_list ap;
int i;
// Find required length to store merged string
int len = 1; // room for NULL
va_start(ap, count);
for(i=0 ; i<count ; i++)
len += strlen(va_arg(ap, char*));
va_end(ap);
// Allocate memory to concat strings
char *merged = calloc(sizeof(char),len);
int null_pos = 0;
// Actually concatenate strings
va_start(ap, count);
for(i=0 ; i<count ; i++)
{
char *s = va_arg(ap, char*);
strcpy(merged+null_pos, s);
null_pos += strlen(s);
}
va_end(ap);
return merged;
}
Usage
#include <stdio.h> // printf
void println(char *line)
{
printf("%s\n", line);
}
int main(int argc, char* argv[])
{
char *str;
str = concat(0); println(str); free(str);
str = concat(1,"a"); println(str); free(str);
str = concat(2,"a","b"); println(str); free(str);
str = concat(3,"a","b","c"); println(str); free(str);
return 0;
}
Output:
// Empty line
a
ab
abc
Clean-up
Note that you should free up the allocated memory when it becomes unneeded to avoid memory leaks:
char *str = concat(2,"a","b");
println(str);
free(str);
I'll assume you need it for one-off things. I'll assume you're a PC developer.
Use the Stack, Luke. Use it everywhere. Don't use malloc / free for small allocations, ever.
#include <string.h>
#include <stdio.h>
#define STR_SIZE 10000
int main()
{
char s1[] = "oppa";
char s2[] = "gangnam";
char s3[] = "style";
{
char result[STR_SIZE] = {0};
snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3);
printf("%s\n", result);
}
}
If 10 KB per string won't be enough, add a zero to the size and don't bother, - they'll release their stack memory at the end of the scopes anyway.
You should use strcat, or better, strncat. Google it (the keyword is "concatenating").
You cannot add string literals like that in C. You have to create a buffer of size of string literal one + string literal two + a byte for null termination character and copy the corresponding literals to that buffer and also make sure that it is null terminated. Or you can use library functions like strcat.
Concatenate Strings
Concatenating any two strings in C can be done in atleast 3 ways :-
1) By copying string 2 to the end of string 1
#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
char str1[MAX],str2[MAX];
int i,j=0;
printf("Input string 1: ");
gets(str1);
printf("\nInput string 2: ");
gets(str2);
for(i=strlen(str1);str2[j]!='\0';i++) //Copying string 2 to the end of string 1
{
str1[i]=str2[j];
j++;
}
str1[i]='\0';
printf("\nConcatenated string: ");
puts(str1);
return 0;
}
2) By copying string 1 and string 2 to string 3
#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
char str1[MAX],str2[MAX],str3[MAX];
int i,j=0,count=0;
printf("Input string 1: ");
gets(str1);
printf("\nInput string 2: ");
gets(str2);
for(i=0;str1[i]!='\0';i++) //Copying string 1 to string 3
{
str3[i]=str1[i];
count++;
}
for(i=count;str2[j]!='\0';i++) //Copying string 2 to the end of string 3
{
str3[i]=str2[j];
j++;
}
str3[i]='\0';
printf("\nConcatenated string : ");
puts(str3);
return 0;
}
3) By using strcat() function
#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
char str1[MAX],str2[MAX];
printf("Input string 1: ");
gets(str1);
printf("\nInput string 2: ");
gets(str2);
strcat(str1,str2); //strcat() function
printf("\nConcatenated string : ");
puts(str1);
return 0;
}
Without GNU extension:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char str1[] = "First";
const char str2[] = "Second";
char *res;
res = malloc(strlen(str1) + strlen(str2) + 1);
if (!res) {
fprintf(stderr, "malloc() failed: insufficient memory!\n");
return EXIT_FAILURE;
}
strcpy(res, str1);
strcat(res, str2);
printf("Result: '%s'\n", res);
free(res);
return EXIT_SUCCESS;
}
Alternatively with GNU extension:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char str1[] = "First";
const char str2[] = "Second";
char *res;
if (-1 == asprintf(&res, "%s%s", str1, str2)) {
fprintf(stderr, "asprintf() failed: insufficient memory!\n");
return EXIT_FAILURE;
}
printf("Result: '%s'\n", res);
free(res);
return EXIT_SUCCESS;
}
See malloc, free and asprintf for more details.
#include <string.h>
#include <stdio.h>
int main()
{
int a,l;
char str[50],str1[50],str3[100];
printf("\nEnter a string: ");
scanf("%s",str);
str3[0]='\0';
printf("\nEnter the string which you want to concat with string one: ");
scanf("%s",str1);
strcat(str3,str);
strcat(str3,str1);
printf("\nThe string is %s\n",str3);
}
using memcpy
char *str1="hello";
char *str2=" world";
char *str3;
str3=(char *) malloc (11 *sizeof(char));
memcpy(str3,str1,5);
memcpy(str3+strlen(str1),str2,6);
printf("%s + %s = %s",str1,str2,str3);
free(str3);
my here use asprintf
sample code:
char* fileTypeToStr(mode_t mode) {
char * fileStrBuf = NULL;
asprintf(&fileStrBuf, "%s", "");
bool isFifo = (bool)S_ISFIFO(mode);
if (isFifo){
asprintf(&fileStrBuf, "%s %s,", fileStrBuf, "FIFO");
}
...
bool isSocket = (bool)S_ISSOCK(mode);
if (isSocket){
asprintf(&fileStrBuf, "%s %s,", fileStrBuf, "Socket");
}
return fileStrBuf;
}
In C, you don't really have strings, as a generic first-class object. You have to manage them as arrays of characters, which mean that you have to determine how you would like to manage your arrays. One way is to normal variables, e.g. placed on the stack. Another way is to allocate them dynamically using malloc.
Once you have that sorted, you can copy the content of one array to another, to concatenate two strings using strcpy or strcat.
Having said that, C do have the concept of "string literals", which are strings known at compile time. When used, they will be a character array placed in read-only memory. It is, however, possible to concatenate two string literals by writing them next to each other, as in "foo" "bar", which will create the string literal "foobar".

Resources