Advertising (This ad goes away for registered users. You can Login or Register)

[Tutorial] Introduction to programming using C (VI)

Discuss about your favorite (gaming...or not) devices here. The most popular ones will end up getting their own categories
Programming discussions for your favorite Device
Forum rules
Forum rule Nº 15 is strictly enforced in this subforum.
User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

[Tutorial] Introduction to programming using C (VI)

Post by m0skit0 » Sat May 21, 2011 2:21 pm

Back to index
<< Prev Next >>

Variables: working with character strings

As I said previously, working with character strings is a bit different than numeric data types. For C, the char* data type used to represent a character string data type is a mere indicator on where the string is.

Thus it doesn't reserve memory space for the string, contrary to the numeric or char data types. You have no space to store a string if you just declare it this way:

Code: Select all

char* string;
This just means string is an "indicator" (it's actually called a "pointer", but we'll get into this later) for a string. But C compiler does not create any space for you to store the string.

Image

On the other hand, declaring it like this:

Code: Select all

char* string = "Hello";
Makes the C compiler create space for that string length, namely 6 characters, store that string character there, and assign the indicator to the string variable.

Image

There's also another way to make the compiler create space without having to define any default string, like this:

Code: Select all

char string[80];
The string variable is now an indicator to a space for a string that's 80 characters long.

Since the char* and char[] data types are mere indicators, we cannot copy a string like this:

Code: Select all

char* string0 = "Hello";
char string1[20];
string1 = string0;
because we would be assigning the indicator, and not its contents. So we have to use functions defined in string.h. Here's an example:

Code: Select all

#include <stdio.h>
// Functions to work with strings
#include <string.h>

int main(void)
{
	// Declaring and assigning value to two character strings
	char* string0 = "Hello world!";
	char* string1 = "This is just\n\tanother sad string";
	
	// Declaring an empty string with a capacity for 100 characters
	char string2[100];
	
	// Setting the buffer to all zeroes (ASCII code 0, NUL character)
	memset(string2, 0, 100);
	
	printf("string0 = %s\n", string0);
	printf("string1 = %s\n", string1);
	
	// Getting string0 length with strlen()
	unsigned int len_string0 = strlen(string0);
	
	// Showing both strings length
	// Notice how we can also directly use an expression for printf arguments
	printf("string0 length = %u\n", len_string0);
	printf("string1 length = %u\n", strlen(string1));
	
	// Copy one string into a string buffer
	strcpy(string2, string0);
	printf("string2 = %s\n", string2);
	
	// Copies only n characters from the beginning of one string to another
	strncpy(string2, string0, 5);
	printf("string2 = %s\n", string2);
	
	// Concatenate strings
	// string1 is appended to the end of string2
	strcat(string2, string1);
	printf("string2 = %s\n", string2);
	
	// Find a substring
	printf("strstr(string1, \"just\") -> %s\n", strstr(string1, "just"));
	
	// Comparing strings
	// strcmp gives (returns) value 0 if strings are equal. For meaning of other values, check strcmp manual.
	int cmp0 = strcmp(string0, "Hello world!");
	int cmp1 = strcmp("This is just another sad string\n", string1);
	
	printf("Comparing string0 vs 'Hello world!' -> %d\n", cmp0);
	printf("Comparing 'This is just another sad string\\n' vs string1 -> %d\n", cmp1);
		
	strcpy(string2, string0);
	int cmp2 = strcmp(string0, string2);
	printf("Comparing string0 vs string2 -> %d\n", cmp2);

	return 0;
}
Ok so now I'm going to post some code fragments and if you like you can comment what do you think about them: are they ok? are they wrong? what's wrong with them? extra comments?

Code: Select all

char* s1;
char* s2 = "Hi there mateys!";
strcpy(s1, s2);
printf("%s = %s\n", s1, s2);

Code: Select all

char* s1 = "Lolcats";
char* s2 = "Hi there mateys!";
strcpy(s1, s2);
printf("%s = %s\n", s1, s2);

Code: Select all

char* s2 = "Hi there mateys!";
char* s1 = s2;
printf("%s = %s\n", s1, s2);

Code: Select all

char s1[100];
char s2 = "Mommy";
char s3 = "Daddy";
strcpy(s1, s2);
strcat(s1, " and ");
strcat(s1, s3);
printf("%s\n", s1);
And for you to practice, some exercises:
  • Make a program that shows a string and a new line without writing any \n character on the printf line.
  • Make a program that concatenates 2 strings and shows the resulting string and its length.
  • Make a program that shows the average length of 4 strings.
  • Make a program that having the string "Hello dang world", manipulates it and prints "Hello world".
  • Make a program that erases everything on a string after the string "me" (this one included).
<< Prev Next >>
Advertising
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

Wdingdong
Posts: 92
Joined: Tue Aug 02, 2011 5:34 pm

Re: [Tutorial] Introduction to programming using C (VI)

Post by Wdingdong » Wed May 23, 2012 12:19 pm

I've studied this tutorial and also done the homework.

Okay, about these given codes:

Code: Select all

char* s1;
char* s2 = "Hi there mateys!";
strcpy(s1, s2);
printf("%s = %s\n", s1, s2);
The string s1 initialization is wrong in the first line.It should be directly given value or it should be initialized like this:char s1[];. IDK, but the code runs fine.

Code: Select all

char* s1 = "Lolcats";
char* s2 = "Hi there mateys!";
strcpy(s1, s2);
printf("%s = %s\n", s1, s2);
The string s1 is small than the s2. Hence, while copying s2 to s1 the program goes into trouble.

Code: Select all

char* s2 = "Hi there mateys!";
char* s1 = s2;
printf("%s = %s\n", s1, s2);
In the second line, value cannot be assigned like that to a string. But again, the program runs fine.

Code: Select all

char s1[100];
char s2 = "Mommy";
char s3 = "Daddy";
strcpy(s1, s2);
strcat(s1, " and ");
strcat(s1, s3);
printf("%s\n", s1);
Line 2 and 3: s2 and s3 are declared as char type and not char* ;)

And now the exercise:

Make a program that shows a string and a new line without writing any \n character on the printf line.
[spoiler]

Code: Select all

#include<stdio.h>
#include<string.h>

int main()
{

	char* string = "And the new line is\nHere!!";                    //Using the \n here instead of printf()
	printf("%s",string);
	return 0;
}
[/spoiler]
Make a program that concatenates 2 strings and shows the resulting string and its length.
[spoiler]

Code: Select all

#include<stdio.h>
#include<string.h>

int main()
{
	int len;
	char* s1 = "East";
	char* s2 = "West";
	char s3[50];
	strcpy(s3,s1);                                 //copying first string in third
	strcat(s3,s2);                                 //adding the second string to the third
	len = strlen(s3);
	printf("%s is %d characters long",s3,len);
	return 0;
}
[/spoiler]
Make a program that shows the average length of 4 strings.
[spoiler]

Code: Select all

#include<stdio.h>
#include<string.h>

int main()
{
	float avg, s1len, s2len, s3len, s4len;
	char* s1 = "Longest";
	char* s2 = "Longer";
	char* s3 = "Long";
	char* s4 = "Small";
	s1len = strlen(s1);
	s2len = strlen(s2);
	s3len = strlen(s3);
	s4len = strlen(s4);
	avg = (s1len+s2len+s3len+s4len)/4.0;
	printf("The average length of the strings %s ,%s ,%s and %s is %f",s1,s2,s3,s4,avg);
	return 0;
}
[/spoiler]
Make a program that having the string "Hello dang world", manipulates it and prints "Hello world".
[spoiler]

Code: Select all

#include<stdio.h>
#include<string.h>

int main()
{
	char s1[50];
	char* s = "Hello dang world";
	printf("Original string: %s\n",s);
	strncpy(s1,s,5);					//Copying the first 5 letters of s into s1
	strcat(s1,strstr(s," world"));		//Concatenating s1 with only "world" of s. Not done directly.
	printf("After manipulating: %s",s1);
	return 0;
}
[/spoiler]
Make a program that erases everything on a string after the string "me"
-I didn't understand this question.
Advertising
// Big thanks to people who share information !!!

User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: [Tutorial] Introduction to programming using C (VI)

Post by m0skit0 » Wed May 23, 2012 2:02 pm

Wow, nice to see someone actually cares about this. I mainly didn't continue this series because nobody seemed to care, so why should I waste my time on it? ;)
Wdingdong wrote:The string s1 initialization is wrong in the first line. It should be directly given value or it should be initialized like this:char s1[];. IDK, but the code runs fine.
Correct, you spotted the bug, but your explanation is wrong. What if I don't want to give it a value? char s1[] is the same as char* s1, so that answer is incorrect. Also the program running fine doesn't mean the code is correct. It runs fine now. Try putting a very large string in s2 and see what happens. The problem with this is what has been told on the article: s1 has no reserved space whatsoever, so when using strcpy() over s1, you're actually writing in non-reserved memory, which could be anywhere, potentially overwriting other important data or even code. You should reserve memory for it, either initializing it statically like char s1[MAX_SIZE) or dynamically using malloc().
Wdingdong wrote:The string s1 is small than the s2. Hence, while copying s2 to s1 the program goes into trouble.
Correct. The problem is the same as previous one basically.
Wdingdong wrote:In the second line, value cannot be assigned like that to a string. But again, the program runs fine.
Nope, the code is correct depending of what the programmer wanted to do. The "problem" lies in that that line doesn't copy the string, but copies the pointer to the string. That is, both s1 and s2 point to the same string (aka same memory place) and thus if you modify one of them, you'll be modifying the other one as well.
Wdingdong wrote:Line 2 and 3: s2 and s3 are declared as char type and not char* ;)
This one was easy :mrgreen: Good job ;)

About the exercises, they're all good. Nice job ;)
Wdingdong wrote:Make a program that erases everything on a string after the string "me"
-I didn't understand this question.
The program has to take a string and remove everything after the substring "me". Example: Input -> "Hello this is me and my friend" // Output -> "Hello this is me".
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

Wdingdong
Posts: 92
Joined: Tue Aug 02, 2011 5:34 pm

Re: [Tutorial] Introduction to programming using C (VI)

Post by Wdingdong » Wed May 23, 2012 5:16 pm

m0skit0 wrote:I mainly didn't continue this series because nobody seemed to care, so why should I waste my time on it?
No problem sir. I'm already enough fortunate to be in your company.
m0skit0 wrote:Try putting a very large string in s2 and see what happens.
The program does not run, just like the second code.
m0skit0 wrote:Nope, the code is correct depending of what the programmer wanted to do. The "problem" lies in that that line doesn't copy the string, but copies the pointer to the string. That is, both s1 and s2 point to the same string (aka same memory place) and thus if you modify one of them, you'll be modifying the other one as well.
Cool. Got it.
m0skit0 wrote: Good job
Thank you.

And the last exercise question:
This was tough. Here's my logic:

Code: Select all

#include<stdio.h>
#include<string.h>

int main()
{
	char* s = "You can find me on Wololo.net/talk";
	char* x = strstr(s, "me");
	char t[50];
	int slen = strlen(s);
	int xlen = strlen(x);
	strncpy(t,s,(slen-xlen+2));		//total length - length of x(me on Wololo.net/talk) + 2(for including me)
	printf("%s",t);
	return 0;
}
IDK why, but in the output after the sentence 'You can find me' there are two-three unknown symbols like 'w׈xß'. And they change in every output.
// Big thanks to people who share information !!!

User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: [Tutorial] Introduction to programming using C (VI)

Post by m0skit0 » Wed May 23, 2012 8:05 pm

Code: Select all

 char* x = strstr(s, "me");
This line is wrong. This is the same we discussed above:
m0skit0 wrote:The problem with this is what has been told on the article: s1 has no reserved space
You haven't reserved space for x in this case. It's only a pointer.
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

Wdingdong
Posts: 92
Joined: Tue Aug 02, 2011 5:34 pm

Re: [Tutorial] Introduction to programming using C (VI)

Post by Wdingdong » Thu May 24, 2012 7:56 am

m0skit0 wrote:

Code: Select all

 char* x = strstr(s, "me");
This line is wrong. This is the same we discussed above:
m0skit0 wrote:The problem with this is what has been told on the article: s1 has no reserved space
You haven't reserved space for x in this case. It's only a pointer.
Oh, yeah, sorry. Fixed it.

Code: Select all

#include<stdio.h>
#include<string.h>

int main()
{
	char* s = "You can find me on Wololo.net/talk";
	char x[50];
	strcpy(x,strstr(s,"me"));
	char t[50];
	int slen = strlen(s);
	int xlen = strlen(x);
	strncpy(t,s,(slen-xlen+2));		//total length - length of x(me on Wololo.net/talk) + 2(for including me)
	printf("%s",t);
	return 0;
}
BTW, do you had the same logic as me or something different?
// Big thanks to people who share information !!!

User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: [Tutorial] Introduction to programming using C (VI)

Post by m0skit0 » Thu May 24, 2012 9:34 am

Code: Select all

strcpy(x,strstr(s,"me"));
Why this? It's superfluous, you're not using x string for anything. Try to avoid doing useless operations (specially with strings) ;)
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

Wdingdong
Posts: 92
Joined: Tue Aug 02, 2011 5:34 pm

Re: [Tutorial] Introduction to programming using C (VI)

Post by Wdingdong » Thu May 24, 2012 10:01 am

Point noted 8-)
Thanks for the detailed explanations(I won't get such details any where).
// Big thanks to people who share information !!!

User avatar
ChemDog
Posts: 139
Joined: Wed Dec 14, 2011 11:39 pm

Re: [Tutorial] Introduction to programming using C (VI)

Post by ChemDog » Thu May 31, 2012 6:59 am

Make a program that shows a string and a new line without writing any \n character on the printf line.
Make a program that concatenates 2 strings and shows the resulting string and its length.
Make a program that shows the average length of 4 strings. I just combined these three into one.
[spoiler]

Code: Select all

#include <stdio.h>
#include <string.h>

int main()
{
char* s1 = "New\nLine\n";
char* s2 = "Another string!";
char* s4 = "And another string.";
char* s5 = "Yet another string.";
char s3[100];
strcpy(s3, s1);
strcat(s3, s2);
strcat(s3, s4);
strcat(s3, s5);
unsigned int len_s3 = strlen(s3);
int x = len_s3;
int y = 4;
int z = x / y;
printf("%s and the length is: %u\n",s3 , len_s3);
printf("The average length of these four strings is: %d\n", z);

return 0;
}
[/spoiler]
Make a program that having the string "Hello dang world", manipulates it and prints "Hello world".
[spoiler]

Code: Select all

#include <stdio.h>
#include <string.h>

int main()
{
char* s1 = ("Hello dang world");
char s2[50];
strncpy(s2, s1, 6);
strcat(s2, strstr(s1, "world"));
printf("%s\n", s2);
}
[/spoiler]
Make a program that erases everything on a string after the string "me"
[spoiler]

Code: Select all

#include <stdio.h>
#include <string.h>

int main()
{
char* s1 = ("I am me, you are you.");
char s2[10];
strncpy(s2, s1 , 7);
printf("%s\n", s2);

return 0;
}
[/spoiler]

User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: [Tutorial] Introduction to programming using C (VI)

Post by m0skit0 » Thu May 31, 2012 2:56 pm

Cool ;)
ChemDog wrote:Make a program that shows the average length of 4 strings. I just combined these three into one.
Wrong, the average is not correctly calculated and shown. Average could be a decimal. You're rounding it down using int.
ChemDog wrote:Make a program that erases everything on a string after the string "me"
Wrong. The program should be able to handle any string.
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

Post Reply

Return to “Programming and Security”