Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

newbie C program crashes

Status
Not open for further replies.

DougP

MIS
Dec 13, 1999
5,985
US
Code:
#include <stdlib.h>
void copy1( char *s1, const char *s2 );
int main(){
	char *str="Hello";
	char Wordarray[5] ;
	int a;
	char m;
	copy1(Wordarray, str);
	for (a=0;a<sizeof(Wordarray);a++){
		m=Wordarray[a];
		
		[COLOR=red]printf("m=%s\n", m);[/color] /*<<< if I comment this line it runs  */
	}
	
	return 0;
}
void copy1( char *s1, const char *s2 )
{
   int i; /* counter */

   /* loop through strings */
   for ( i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ ) {
      ; /* do nothing in body */
   } /* end for */
} /* end function copy1 */
the program compiles but won't run. Error "sorry for the inconvience but have to close"
What am I doing wrong?

DougP
[r2d2] < I Built one
 
m" is only a char and you're telling printf to use %s. try switching %s to %c.


also you may want to define "Wordarray" with some kind of constant, and then use that constant as your for loops condition statement:

Code:
#define ARRAY_SIZE 5

int main()
{
...
char Wordarray[ARRAY_SIZE];
...

for(int i = 0; i < ARRAY_SIZE; i++)
{
m = Wordarray[i];
}

}

also, i dont know if this is the desired result, but essentially the for loop in main is assigning the last element of Wordarray to m.
 
thank you for your quick response.
no it's not the desired result I want to print out each character one at a time. I really need to reverse the letters
like "Hello" and make it "olleH"
but I could not get this part to work at all after days of frustration. I'm a Basic language guy and I really don't like ANSI C.


DougP
[r2d2] < I Built one
 
you would want something like this then:

Code:
char Wordarray[ARRAY_SIZE]
char BackwardArray[ARRAY_SIZE]


int j = 0;
for(int i = ARRAY_SIZE - 1; i >= 0; i--, j++)
{
//i starts at the last element of Wordarray
//j starts at the first element of BackwardArray
//decrease i to work backward through Wordarray
//while building from element 0(zero) in backward array
BackwardArray[j] = Wordarray[i];
}
 
I'm sorry missed the curly brackets for the for loop, so you can disregard my statement about only assigning the last element to "m." however, given my example from above you should just be able to print out the new BackwardArray, as it would be build in reverse... if you want to use what you already have written you should switch your initialization and condition of the for loop:

Code:
for(a = ARRAY_SIZE - 1; a >= 0; a--)
...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top