473,324 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Learning pointers

Can someone take a look at my code and let me know if you see any
mistakes?

========================

#include <stdio.h>
#include <ctype.h>
#include <conio.h> // Used to make the getch() work
#include <string.h>

int main(void)
{

// Declare variables
// -----------------

char text[70];
char *txtptr;

// Prompt user for line of text
// ----------------------------

printf ("\nEnter a line of text (up to 69 characters):\n");
fgets(text,sizeof text,stdin);

// Ensure that the string terminator is no more than the last
// element in the array.
// -----------------------------------------------------------

txtptr = text;
*(txtptr + strlen(txtptr) - 1) = '\0';

// Converts and outputs the text in uppercase characters.
// ----------------------------------------------------

printf ("\nThe line of text in uppercase is:\n");

txtptr = text;
while (*txtptr != '\0')
putchar( toupper(*txtptr++) );

// Converts and outputs the text in uppercase characters.
// ----------------------------------------------------

printf ("\n\nThe line of text in lowercase is:\n");

txtptr = text;
while ( *txtptr != '\0')
putchar( tolower(*txtptr++));
putchar('\n');

printf("\n");

getch(); // Pauses output

return 0;

} // end main
Nov 13 '05 #1
10 3571
Ma*********@home.com wrote:
Can someone take a look at my code and let me know if you see any
mistakes? printf ("\nEnter a line of text (up to 69 characters):\n");
fgets(text,sizeof text,stdin); // Ensure that the string terminator is no more than the last
// element in the array.
// -----------------------------------------------------------

txtptr = text;
*(txtptr + strlen(txtptr) - 1) = '\0';


This won't work. If 'text' does not alrealy contain a '\0' at the
end you can't use strlen() because all it does is count the number
of chars until it hits '\0', so if there isn't one strlen() won't
be able to figure out where the string ends. I understand that you
wrote it this way to use pointers but here a simple

*(txtptr + sizeof text - 1) = '\0';

is what you need.
Regards, Jens
--
_ _____ _____
| ||_ _||_ _| Je***********@physik.fu-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oerring
Nov 13 '05 #2
>> txtptr = text;
*(txtptr + strlen(txtptr) - 1) = '\0';


This won't work. If 'text' does not alrealy contain a '\0' at the
end you can't use strlen() because all it does is count the number
of chars until it hits '\0', so if there isn't one strlen() won't
be able to figure out where the string ends. I understand that you
wrote it this way to use pointers but here a simple

*(txtptr + sizeof text - 1) = '\0';

is what you need.
Regards, Jens


=========================

Hey Jens,

When I add that code I get the following warning:

local variable 'txtptr' used without having been initialized

How should I initialize the variable? Just set it equal to zero?

Here is my updated code:

#include <stdio.h>
#include <ctype.h>
#include <conio.h> // Used to make the getch() work
#include <string.h>

int main(void)
{

// Declare variables
// -----------------

char text[70];
char *txtptr;

// Prompt user for line of text
// ----------------------------

printf ("\nEnter a line of text (up to 69 characters):\n");
fgets(text,sizeof text,stdin);

// Ensure that the string terminator is no more than the last
// element in the array.
// -----------------------------------------------------------

*(txtptr + sizeof text - 1) = '\0';

// Converts and outputs the text in uppercase characters.
// ----------------------------------------------------

printf ("\nThe line of text in uppercase is:\n");

txtptr = text;
while (*txtptr != '\0')
putchar( toupper(*txtptr++) );

// Converts and outputs the text in uppercase characters.
// ----------------------------------------------------

printf ("\n\nThe line of text in lowercase is:\n");

txtptr = text;
while ( *txtptr != '\0')
putchar( tolower(*txtptr++));
putchar('\n');

printf("\n");

getch(); // Pauses output until the user presses a button on
the keyboard.

return 0;

} // end main

Nov 13 '05 #3
Ma*********@home.com wrote:
#include <stdio.h>
#include <ctype.h>
#include <conio.h> // Used to make the getch() work
#include <string.h>

int main(void)
{

// Declare variables
// -----------------
Be careful with this kind of comment. They add nothing to the code
except that they restate the obvious; they can confuse the reader into
thinking something non-obvious is going on (after all, why else
comment?) when there isn't; and because they tend to get ignored, they
can easily get out of sync with the code.
It's much better not to comment on _what_ is done, but on _why_ it is
done. Everybody can figure out that you declare variables here, but it's
sometimes useful to know what a particular variable is intended to be
used for.
char text[70];
char *txtptr; printf ("\nEnter a line of text (up to 69 characters):\n");
fgets(text,sizeof text,stdin);
Note that this doesn't prevent the user from entering more than 69
characters; the rest will remain in the input stream, waiting for your
next input function.
// Ensure that the string terminator is no more than the last
// element in the array.
This comment does not even make sense. You do nothing below with the
last element in the array. You do something near the last element of the
_string_, which is a different thing. And the last character of a string
is _always_ the null terminator - that's what makes it a string, not an
unterminated char array.
txtptr = text;
*(txtptr + strlen(txtptr) - 1) = '\0';
What you do here, in a roundabout way, is overwrite the last character
before the string terminator. You do this regardless of whether there is
a last character at all; moreover, you do this regardless of what that
character actually is.
What I suspect you really wanted to do is to remove the newline
character which fgets() tends to leave in the string. If so, note that
this newline is not necessarily there: it is only there if your user
entered it. It could be missing if, e.g., the user enters a string of
more than seventy characters - the first seventy will be put into text,
and the rest, including the newline, will remain in the input stream.
It's also possible that you get your input piped from a file, and the
line you read happens to be the last line in the file - but does not end
in a newline. In that case, there won't be a newline in the resulting
string, either.
So what you want to do is:
- check that there is a newline in text;
- if so, overwrite it, but if not, overwrite nothing.

One way to do this is

if ((txtptr=strchr(text, '\n')) *txtptr='\0';
// Converts and outputs the text in uppercase characters.
This converts nothing. It merely prints the upper-case equivalent of the
input.
printf ("\nThe line of text in uppercase is:\n");

txtptr = text;
while (*txtptr != '\0')
putchar( toupper(*txtptr++) );
First of all, toupper() takes an int, requires that its input is in the
range of _unsigned_ char, or EOF. If your char happens to be signed, and
you enter a character with a negative value, this call can result in
some... creative values.
Second, this is the perfect place for a for-loop.

for (txtptr=text; *txtptr!='\0'; txtptr++)
putchar(toupper((unsigned char)*txtptr);

Ditto for the lowercase loop.
putchar('\n');

printf("\n");


Why these two different calls? They do exactly the same thing...

Richard
Nov 13 '05 #4
On Wed, 9 Jul 2003 Ma*********@home.com wrote:
txtptr = text;
*(txtptr + strlen(txtptr) - 1) = '\0';
This won't work. If 'text' does not alrealy contain a '\0' at the
end you can't use strlen() because all it does is count the number
of chars until it hits '\0', so if there isn't one strlen() won't
be able to figure out where the string ends. I understand that you
wrote it this way to use pointers but here a simple

*(txtptr + sizeof text - 1) = '\0';

is what you need.
Regards, Jens


=========================

Hey Jens,

When I add that code I get the following warning:

local variable 'txtptr' used without having been initialized

How should I initialize the variable? Just set it equal to zero?

Here is my updated code:

#include <stdio.h>
#include <ctype.h>
#include <conio.h> // Used to make the getch() work
#include <string.h>

int main(void)
{

// Declare variables
// -----------------

char text[70];
char *txtptr;

// Prompt user for line of text
// ----------------------------

printf ("\nEnter a line of text (up to 69 characters):\n");


Minor enhancement:

printf ("\nEnter a line of text (up to %d characters):\n",
sizeof(text)-1);

By doing this, the number 69 changes automatically when you change the
size of the array.
fgets(text,sizeof text,stdin);

// Ensure that the string terminator is no more than the last
// element in the array.
// -----------------------------------------------------------

*(txtptr + sizeof text - 1) = '\0';
The variable txtptr is not initialized. This line of code is saying, "take
the address in txtptr, add the size of the array text then subtract 1, go
to that address and store the null character." If we have not assigned an
address to txtptr then it is unclear what address will we get. You need to
give txtptr an address.

I believe what you are doing here is attempt to set text[69] to null
character. Why you are using the txtptr is not clear to me. I would just
use:

text[sizeof(text)-1] = '\0';
// Converts and outputs the text in uppercase characters.
// ----------------------------------------------------

printf ("\nThe line of text in uppercase is:\n");

txtptr = text;
while (*txtptr != '\0')
putchar( toupper(*txtptr++) );
This seems pretty clear. A good use of txtptr. If there is no newline
character it might cause a problem with your display. You might want to
add a putchar('\n');
// Converts and outputs the text in uppercase characters.
// ----------------------------------------------------
I'm guessing that this comment is wrong. The code below prints the string
as all lowercase.
printf ("\n\nThe line of text in lowercase is:\n");

txtptr = text;
while ( *txtptr != '\0')
putchar( tolower(*txtptr++));
putchar('\n');
Looks good.
printf("\n");
Odd that you use putchar('\n') and then printf("\n"); I would have
preferred two putchar('\n'); calls, one printf("\n\n"); or possibly one
puts("\n");
getch(); // Pauses output until the user presses a button on
the keyboard.

return 0;

} // end main


--
main(){int j=1234;char t[]=":@abcdefghijklmnopqrstuvwxyz.\n",*i=
"iqgbgxmdbjlgdv.lksrqek.n";char *strchr(const char *,int);while(
*i){j+=strchr(t,*i++)-t;j%=sizeof t-1;putchar(t[j]);} return 0;}

Nov 13 '05 #5
Ma*********@home.com wrote:
Can someone take a look at my code and let me know if you see any
mistakes?

========================

#include <stdio.h>
#include <ctype.h>
#include <conio.h> // Used to make the getch() work
#include <string.h>

int main(void)
{ <snip> getch(); // Pauses output

return 0;

} // end main


In addition to other people's comments, I'd like to add that calling
getch() (a non-standard function) just before your main returns is
merely a _useless_ *kludge*.

If the aim is that the execution window doesn't disappear as soon as
execution ends, then learn how to use your IDE and how to modify that
behaviour. This problem does not have to, and thus should not have to,
be solved in your code.
--
Bertrand Mollinier Toublet
"Reality exists" - Richard Heathfield, 1 July 2003

Nov 13 '05 #6


Ma*********@home.com wrote:
<snip> When I add that code I get the following warning:

local variable 'txtptr' used without having been initialized

How should I initialize the variable? Just set it equal to zero?

Here is my updated code:

#include <stdio.h>
#include <ctype.h>
#include <conio.h> // Used to make the getch() work
#include <string.h>

int main(void)
{

// Declare variables
// -----------------

char text[70];
char *txtptr;

// Prompt user for line of text
// ----------------------------

printf ("\nEnter a line of text (up to 69 characters):\n");
fgets(text,sizeof text,stdin);

Test the return code.

// Ensure that the string terminator is no more than the last
// element in the array.
// -----------------------------------------------------------

*(txtptr + sizeof text - 1) = '\0';
You shouldn't have deleted the preceding "txtptr = text" line, hence your
compiler warning.
// Converts and outputs the text in uppercase characters.
// ----------------------------------------------------

printf ("\nThe line of text in uppercase is:\n");

txtptr = text;
while (*txtptr != '\0')
putchar( toupper(*txtptr++) );


Indent this so it's obvious that the putchar is within the loop. Also, although
you don't syntactically NEED an { ... } in the while loop since you're just
doing one thing, adding them anyway makes the code slightly more future-proof.
For example, if we have the above code written as:

a) while (*txtptr != '\0')
putchar( toupper(*txtptr++) );

b) while (*txtptr != '\0') {
putchar( toupper(*txtptr++) );
}

then if you or somone else comes along in future and adds, say, a debugging
print statement like:

a') while (*txtptr != '\0')
fprintf(stderr,"writing a char\n");
putchar( toupper(*txtptr++) );

b') while (*txtptr != '\0') {
fprintf(stderr,"writing a char\n");
putchar( toupper(*txtptr++) );
}

then in the case of "a'", they've just broken the code by pushing the "putchar"
outside of the loop, whereas in "b'" it'll work as intended. Ditto for any other
loops and "if" statements.

Ed.

Nov 13 '05 #7
In 'comp.lang.c', Ma*********@home.com wrote:
#include <stdio.h>
#include <ctype.h>
#include <conio.h> // Used to make the getch() work
You don't this not portable extension at the moment.
#include <string.h>

int main(void)
{

// Declare variables
// -----------------

char text[70];
char *txtptr;

// Prompt user for line of text
// ----------------------------

printf ("\nEnter a line of text (up to 69 characters):\n");
fgets(text,sizeof text,stdin);
Good.
// Ensure that the string terminator is no more than the last
// element in the array.
// -----------------------------------------------------------

txtptr = text;
*(txtptr + strlen(txtptr) - 1) = '\0';
For this behaviour, you don't need the pointer:

text[strlen(test) - 1] = 0;

is fine, but not the best way of doing it. If you are not scared by data
recycling, you can use the pointer to search and kill the '\n'.

txtptr = strchr (text, '\n');
if (txtptr)
{
*txtptr = 0;
}
// Converts and outputs the text in uppercase characters.
// ----------------------------------------------------

printf ("\nThe line of text in uppercase is:\n");

txtptr = text;
This is what I call 'data recycling'...
while (*txtptr != '\0')
putchar( toupper(*txtptr++) );
Your indentation is scary. Also, I find confusing to have an parameter with a
unary operator. I prefer to make things crystal clear for the reader.
Nowadays compilers are smart enough to provide the required optimization.

Try:

while (*txtptr != '\0')
{
putchar (toupper((unsigned) *txtptr));
txtptr++;
}

<...>
getch(); // Pauses output
getchar ();
return 0;

} // end main


--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
<blank line>
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 13 '05 #8
In 'comp.lang.c', Je***********@physik.fu-berlin.de wrote:
fgets(text,sizeof text,stdin);
txtptr = text;
*(txtptr + strlen(txtptr) - 1) = '\0';


This won't work. If 'text' does not alrealy contain a '\0' at the


That's wrong. 'text' has to contain a zero. This is guaranteed by the
standard, because it has been set by fgets(). (Well, assuming the second
parameter of fgets() is > 0, and the return of fgets() is not NULL)
end you can't use strlen() because all it does is count the number
of chars until it hits '\0', so if there isn't one strlen() won't
be able to figure out where the string ends. I understand that you
wrote it this way to use pointers but here a simple

*(txtptr + sizeof text - 1) = '\0';

is what you need.


No. I think you have not got the point. fgets() grabs all the possible
characters, including the final '\n' when there is room enough. What the OP
wanted to do was to get rid of this '\n'. As I have indicated in another post
of this thread, there is a better way to do it.

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
<blank line>
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 13 '05 #9
Hello Again,

Thanks to everyone that helped me to clean up my code! Especially
Emmanuel Delahaye. I spent time understanding and implementing all of
your suggestions. I am re-submitting the final product to the group
in case anyone would like to take a look at the finished product and
alert me to any obvious errors. I know that the comments are
overkill, but my instructor likes us to comment on everything. I
think it is to make sure that we understand what it going on.

Mahalo!

==============================================

/*
---------------------------------------------------------------------------------------------

Write a C program that prompts the user to enter a line of text (up to
69 characters).

It should then convert the text entered to uppercase letters and then
to lowercase letters.

Your program should use a character array: text[70]. It should use the
gets function to prompt
the user for the line of text.

Your program must use pointer notation.

The dialog with the user must look like:

Enter a line of text (up to 69 characters):
ThiS is A LiNe of teXt with UPPERCASE anD lowercase LeTterS!

The line of text in uppercase is:
THIS IS A LINE OF TEXT WITH UPPERCASE AND LOWERCASE LETTERS!

The line of text in lowercase is:
this is a line of text with uppercase and lowercase letters!

----------------------------------------------------------------------------------------------
*/

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

int main(void)
{

// Declare variables
// -----------------

char text[70];
char *txtptr;

// Prompt user for line of text
// ----------------------------

printf ("\nEnter a line of text (up to 69 characters):\n");
fgets(text,sizeof text,stdin);

// Uses the pointer to search and delete the \n from fgets
// -----------------------------------------------------------

txtptr = strchr (text, '\n');
if (txtptr)
{
*txtptr = 0;
}

// Outputs the text in uppercase characters.
// ----------------------------------------------------

printf ("\nThe line of text in uppercase is:\n");

txtptr = text;

while(*txtptr != '\0')
{
putchar (toupper((unsigned) *txtptr));
txtptr++;
}

// Outputs the text in lowercase characters.
// ----------------------------------------------------

printf ("\n\nThe line of text in lowercase is:\n");

txtptr = text;

while(*txtptr != '\0')
{
putchar (tolower((unsigned) *txtptr));
txtptr++;
}

printf("\n");

getchar(); // Pauses output until the user presses a button on
the keyboard.

return 0;

} // end main
Nov 13 '05 #10
In 'comp.lang.c', st*****@home.com wrote:
Thanks to everyone that helped me to clean up my code! Especially
Emmanuel Delahaye.
You are welcome.
I spent time understanding and implementing all of
your suggestions. I am re-submitting the final product to the group
in case anyone would like to take a look at the finished product and
alert me to any obvious errors. I know that the comments are
overkill, but my instructor likes us to comment on everything. I
think it is to make sure that we understand what it going on.
You are on the tracks.
/*
-------------------------------------------------------------------------
--------------------

Write a C program that prompts the user to enter a line of text (up to
69 characters).

It should then convert the text entered to uppercase letters and then
to lowercase letters.

Your program should use a character array: text[70]. It should use the
gets function to prompt
the user for the line of text.

Your program must use pointer notation.

The dialog with the user must look like:

Enter a line of text (up to 69 characters):
ThiS is A LiNe of teXt with UPPERCASE anD lowercase LeTterS!

The line of text in uppercase is:
THIS IS A LINE OF TEXT WITH UPPERCASE AND LOWERCASE LETTERS!

The line of text in lowercase is:
this is a line of text with uppercase and lowercase letters!

-------------------------------------------------------------------------
--------------------- */

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

int main(void)
{

// Declare variables
// -----------------

char text[70];
char *txtptr;

// Prompt user for line of text
// ----------------------------

printf ("\nEnter a line of text (up to 69 characters):\n");
fgets(text,sizeof text,stdin);
You could test the return of fgets() against NULL. It denotes some input
error.
// Uses the pointer to search and delete the \n from fgets
// -----------------------------------------------------------

txtptr = strchr (text, '\n');
if (txtptr)
{
*txtptr = 0;
}
Good.
// Outputs the text in uppercase characters.
// ----------------------------------------------------

printf ("\nThe line of text in uppercase is:\n");

txtptr = text;

while(*txtptr != '\0')
{
putchar (toupper((unsigned) *txtptr));
txtptr++;
}
A '\n' is missing.
// Outputs the text in lowercase characters.
// ----------------------------------------------------

printf ("\n\nThe line of text in lowercase is:\n"); .. ^^--------------------------------------------------+
I think that the first '\n' belongs to the previous bloc of code. --+
txtptr = text;

while(*txtptr != '\0')
{
putchar (tolower((unsigned) *txtptr));
txtptr++;
}

printf("\n");

getchar(); // Pauses output until the user presses a button on
the keyboard.

return 0;

} // end main


Apart these nits, sounds good to me.

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
<blank line>
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 13 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Ryan Walker | last post by:
Hi, I'm getting started with python and have almost zero programming experience. I'm finding that there are tons of tutorials on the internet -- such as the standard tutorial at python.org -- that...
6
by: Kalle Anke | last post by:
Those who have read my posts today have probably understood that I'm not a "true" Python programmer ... but I want to learn more (I think that Python is rather fun). I've read "Learning Python"...
17
by: Javier | last post by:
Hi I'm trying to learn how to use pointers with a little example. I did: void main(int argc, char* argv) { char algo = "Algo mas"; char * p = algo;
8
by: Mantorok | last post by:
Hi all I'm looking to learn C and/or C++ and I was wondering if there were any good on-line resources and books. I am currently a C# developer but I'm keen to discover C/C++ as I feel it...
17
by: Karsten Kvistad | last post by:
Hi! I'm currently teaching myself the C programming language. The problem is I don't know what to do next. I know file I/O, pointers, functions and the like. I do not know how to make .h files,...
1
by: ketema | last post by:
Hello, I was wondering if someone could help me with a function I am trying to write. The purpose of the function is to read in text from a file in the following format: FIRSTNAME LASTNAME...
4
by: Andy | last post by:
Hi I'm in the position where my employer might pay for courses in VB.net or even the complete MCAD certification. But I need some good arguments for learning VB.net that can relate to my current...
36
by: utab | last post by:
Dear, I have experince in C( numerical projects, like engineering problems, scientific applications) I have the basic notion of C++ also, I have read Accelerated C++ until Chapter 7, however it...
26
by: mfasoccer | last post by:
I am sorry if this is an inappropriate place to put this post, if so please delete it. I am wondering about a few things. Do you guys recommend learning C as a second language, as someone who...
6
by: JoeC | last post by:
I understand the basics of pointers, they point to memory locations. I would like to know resources for learning all about poters. I am having some problems erasing elements of pointers from a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.