Hi all,
I'm learning C and trying to find characters in a string array. All my
efforts result in crashing programs. Can anyone see why?
#include <stdio.h>
int main()
{
char strArray[10] = {"abcdefg"};
int i;
int j = strlen(strArray );
for (i = 0; i < j; ++i)
{
char a = strArray[i];
if (a = 'c')
{
printf("%s\n", a);
return 0;
}
}
return 0;
} 30 2766
On Sun, 24 Sep 2006, Richard Heathfield wrote:
pkirk25 said:
<snip>
>char a = strArray[i];
if (a = 'c')
You mean:
if(a == 'c')
>{
printf("%s\n ", a);
You probably mean:
printf("%c\n", a);
It's crashing because you're treating a, a single char, as if it were a
pointer to the first in a whole bunch of char.
... or printf("%s\n", strArray). Also, the OP was calling
strlen without a prototype (undefined behaviour).
Tak-Shing
pkirk25 wrote:
Hi all,
I'm learning C and trying to find characters in a string array. All my
efforts result in crashing programs. Can anyone see why?
#include <stdio.h>
int main()
{
char strArray[10] = {"abcdefg"};
int i;
int j = strlen(strArray );
for (i = 0; i < j; ++i)
{
char a = strArray[i];
if (a = 'c')
{
printf("%s\n", a);
It crashes here because the "%s" code requires that you
provide a matching string argument, but `a' is just a `char'
and not a string. A string is not a single `char', but an
array of `char', one of which has the value zero to mark the
string's end.
Two other points: The `if' statement doesn't do what you
probably intend (go back to your textbook and read about the
difference between the `=' and `==' operators), and you need
to #include the <string.hhead er if you want to use strlen().
--
Eric Sosman es*****@acm-dot-org.invalid
Richard Heathfield wrote:
pkirk25 said:
<snip>
>char a = strArray[i];
if (a = 'c')
You mean:
if(a == 'c')
You can avoid these problems by adapting the habit of putting the
constant first, i.e.:
if ('c' == a) ...
and the compiler will complain if you have only a single '='.
--
Some informative links:
<news:news.anno unce.newusers
<http://www.geocities.c om/nnqweb/>
<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html >
<http://www.netmeister. org/news/learn2quote.htm l>
<http://cfaj.freeshell. org/google/>
Many thanks all. Its allowed me to proceed ot the point where Ic an
find what I want in a string but now it crashes when I try to extract
it to another string.
I've tried several approaches here and all bomb out. Where am I going
wrong please?
#include <stdio.h>
#include <string.h>
int main(void)
{
char strLong[100] = {"Pointer to a confused guy"};
char strDst[100];
int a = 0;
for (a = 0; a < 5; ++a)
{
strcat(strDst, strLong[a]);
}
return 0;
}
pkirk25 wrote:
Hi all,
I'm learning C and trying to find characters in a string array. All my
efforts result in crashing programs. Can anyone see why?
#include <stdio.h>
#include <string.hwill be needed below.
>
int main()
int main(void) is preferred.
{
char strArray[10] = {"abcdefg"};
int i;
int j = strlen(strArray );
for (i = 0; i < j; ++i)
{
char a = strArray[i];
if (a = 'c')
Surely not an assignment. You mean 'if (a == 'c')' don't you?
{
printf("%s\n", a);
I assume you want to print the string beginning with the 'c'.
See below.
return 0;
}
}
return 0;
}
Maybe this is what you mean?
#include <stdio.h>
#include <string.h>
int main(void)
{
char strArray[10] = {"abcdefg"};
int i;
int j = strlen(strArray );
for (i = 0; i < j; ++i) {
char a = strArray[i];
if (a == 'c') {
printf("%s\n", strArray+i);
return 0;
}
}
return 0;
}
Maybe not.
--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
pkirk25 schrieb:
I've tried several approaches here and all bomb out. Where
am I going wrong please?
#include <stdio.h>
#include <string.h>
int main(void)
{
char strLong[100] = {"Pointer to a confused guy"};
strLong contains a string of length 25.
char strDst[100];
strDst isn't a string. Exercise: why not? How would you
make it into a string? Trick question: what does it actually
contain? Why?
>
int a = 0;
for (a = 0; a < 5; ++a)
{
strcat(strDst, strLong[a]);
This line has three problems. First, strLong[a] is not of the
appropriate type for strcat(), so this shouldn't even compile
as it is written here. Second, as mentioned above, strDst
isn't a string; using C's string functions on things that aren't
strings generally means anything at all can (and eventually
will) happen. Third, assuming the first two errors are fixed,
you appear to be trying to stuff 116 chars into a 100 char
array. I trust it is obvious why that's bad.
}
return 0;
}
pkirk25 wrote:
>
Many thanks all. Its allowed me to proceed ot the point where Ic
an find what I want in a string but now it crashes when I try to
extract it to another string.
I've tried several approaches here and all bomb out. Where am I
going wrong please?
#include <stdio.h>
#include <string.h>
int main(void)
{
char strLong[100] = {"Pointer to a confused guy"};
char strDst[100];
int a = 0;
for (a = 0; a < 5; ++a)
{
strcat(strDst, strLong[a]);
}
return 0;
}
The following fixes to avoid undefined behaviour may help.
#include <stdio.h>
#include <string.h>
int main(void)
{
char strLong[100] = {"Pointer to a confused guy"};
char strDst[100] = ""; /* <-- Nota bene */
int a = 0;
while (strlen(strDst) + strlen(&strLong[++a]) + 1 < 100) {
putchar(a + '0');
strcat(strDst, &strLong[a]);
}
puts(strDst);
return 0;
}
--
Some informative links:
<news:news.anno unce.newusers
<http://www.geocities.c om/nnqweb/>
<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html >
<http://www.netmeister. org/news/learn2quote.htm l>
<http://cfaj.freeshell. org/google/>
CBFalconer <cb********@yah oo.comwrites:
Richard Heathfield wrote:
>pkirk25 said:
<snip>
>>char a = strArray[i];
if (a = 'c')
You mean:
if(a == 'c')
You can avoid these problems by adapting the habit of putting the
constant first, i.e.:
if ('c' == a) ...
and the compiler will complain if you have only a single '='.
[...]
Yes, you can, but many people, including me, find that style almost
unbearably ugly.
Train yourself to read "=" as "assign" and "==" as "is equal to".
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Keith Thompson said:
CBFalconer <cb********@yah oo.comwrites:
>Richard Heathfield wrote:
>>pkirk25 said:
<snip>
char a = strArray[i];
if (a = 'c')
You mean:
if(a == 'c')
You can avoid these problems by adapting the habit of putting the constant first, i.e.:
if ('c' == a) ...
and the compiler will complain if you have only a single '='.
[...]
Yes, you can, but many people, including me, find that style almost
unbearably ugly.
Yes, they do, but many people, including me, don't. :-)
Train yourself to read "=" as "assign" and "==" as "is equal to".
That's an excellent idea, although personally I prefer "becomes" over
"assign". Once you've done that, though, that doesn't mean you'll always
type what you meant to type. (And if you've *really* trained yourself to
read "==" as "is equal to", then surely it doesn't matter from a
readability perspective which way round they go.)
Incidentally, around 15 years ago I was debugging a production code bug
report. I spotted the following line merely in passing, as it were - it
wasn't the problem I was looking for, but it was nevertheless most
assuredly a problem:
k == 5;
(That was the exact code. I can't remember what k stood for, let alone 5.)
Unfortunately, no parallel trick of the language exists for forcing the
compiler to detect this kind of error.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999 http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Eric Brunel |
last post by:
Hi all,
I was creating a Tkinter widget in the style of the reversed tabs below Excel
worksheets and I stepped in a serious problem: the code I made makes python
crash with a seg fault, bus error or X11 BadGC error on both Solaris (2.6 and
2.7) and Linux (Mandrake 8.0); it doesn't crash on Windows. I tried to simplify
the script, but I couldn't reproduce the crash with a simpler code. So the code
below is somewhat long; sorry for that.
...
|
by: Andrew Thompson |
last post by:
My brother was saying his friend running IE4
(apparently he's a stubborn techno-geek) has
'severe troubles' with the site I am designing
at http://www.lensescapes.com/
The site has been changed recently (a Java applet
that was causing a 'focus' problem was removed).
I was wonderring if there anybody out there with
access to IE4 could cast a quick browser over it
|
by: roni |
last post by:
hi.
i have application written in vb.net + managed c++ dll that call also to
unmanaged c++ function.
the application crash.
i open the dump file of the crash with WinDbg and that's is the call stack
(using the sos.dll) :
=====================================
|
by: greenflame |
last post by:
First of all I only have IE for testing.
Ok. I have a script that is supposed to show, not evaluate, the
indefinite integral of something. When I run the script it just craches
IE. I have tried to get all the obvious bugs out... Um... The script is
at: http://ali.freezope.org/idf test and what it is supposed to show is
at: http://ali.freezope.org/idf result
|
by: xixi |
last post by:
i have db2 udb v8.1 on windows 64 bit 2003 server, after db2 server
start , i found this in the db2diag.log, is this error?
2004-05-05-15.28.30.780000 Instance:DB2 Node:000
PID:1692(db2syscs.exe) TID:2860 Appid:AC10040A.GD5F.00FC56D8BEC5
base sys utilities sqledint Probe:30
Crash Recovery is needed.
2004-05-05-15.28.31.890000 Instance:DB2 Node:000
| |
by: Adam Louis |
last post by:
I would like help resolving this problem. I'm a novice who's been
hired to query a hospital database and extract useful information,
available to me only in a dynamically generated, downloadable .mdb.
The query below query runs correctly and without error, but any
attempt to save it causes Access to crash without a message, leaving
the .ldb file. Opening the DB reveals it saved a blank "query1".
I've upgraded to Jet SP 8, and I'm running...
|
by: shiry |
last post by:
Hi,
I need to do some important cleanup before my console application
exists. I used the console ctrl event. This is working well and it
fires for all cases, including the CTRL_CLOSE_EVENT (if I close the
application from the X botton). But on
the contrary to what the MSDN indicates
(ms-help://MS.VSCC.2003/MS.MSDNQTR.2003OCT.1033/dllproc/base/handlerroutine.htm),
ending my process from the task manager did not fire the
CTRL_CLOSE_EVENT....
|
by: junw2000 |
last post by:
Below is a simple code:
#include <iostream>
class base{
public:
base(): i(11){std::cout<<"base constructor"<<'\n';}
virtual void f() = 0;
virtual ~base(){ std::cout<<"base destructor"<<'\n';}
int i;
|
by: NewToCPP |
last post by:
Hi,
Why does a C/C++ programs crash?
When there is access to a null pointer or some thing like that programs
crash, but why do they crash?
Thanks.
|
by: benjamin.krulewitch |
last post by:
I'm debugging an issue with a C program that causes the computer to
crash, and I'm attempting to log information immediately before the
crash occurs. I us my BKprintLog function (see below) to write
information into a log file. The problem is, i'm not confident that
information i write to the log gets saved onto the hard drive before
the crash occurs.
My understanding of hard drives and OS are that because hard drives are
so slow,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |