Aia 1,977 Nearly a Posting Maven

>And about C hat and C++ hat, I'll Google and see what they are.
Don't waste your time doing that. What Salem was trying to convey was that people has the tendency to write C/C++ implying that it is, somehow just a programming language. When indeed C is not C++, neither C++ is C, contrary to the believe of many books and new learners. It is better to treat them as they are, two completely different programming languages with some similar syntax.

> new allocates memory in C++ and java, how its different from malloc?
Closely related to the topic. C do not have garbage collector, therefore, every time you call malloc to allocate some block of memory you must make sure that when that memory is not needed you release it by making a call to the function free().
Get to the habit of making sure that each call to malloc needs to be verified by checking that there was not problem reserving that block of memory.
e.g.
example

Not related to the topic, but some how not possible to dismiss are those call to scanf() to read an integer from user. I don't want to overwhelm you, but feeling a waste of time to learn something you are going to have to unlearn later; hence my intention to warn you now.
Don't use scanf() for reading from input. Verifying what the user enters is very hard, specially strings.
Some …

Salem commented: Well said +17
grvs commented: nice tips +1
Aia 1,977 Nearly a Posting Maven

No, this is what it does now. I want to do

tmp = "http://example.com/asdf";

I don't want to take in an argument. The problem is that it breaks when I try to code it myself.

Possible you are trying to modify a 'read only' variable.
Instead of: char *opt_httphost = "http://example.com/asdf"; which is an unchangeable variable,
use: char opt_httphost[] = "http://example.com/asdf"; so later when you try strchr() to search for the remainder '/' and over-write with '\0' you will not try to access memory that is illegal.

Aia 1,977 Nearly a Posting Maven

Would an example help?

#include <stdio.h>
#include <stdlib.h> /* for exit() */
#include <string.h> /* for strlen() */

int main ( int argc, char *argv[] ) {
    
    char *tmp;

/* Is there any arguments */
    if ( argc > 0 ) {
        tmp = argv[1];
    }
    else {
        fprintf( stderr, "format: program_name <URL>" );
        exit(0);
    }

/* If less than 11 chars long is not a proper URL */
    if ( strlen( argv[1] ) > 11 ) {
        tmp += 7; /* advance ahead beyond the http:// */
    }
    else {
        fprintf( stderr, "Invalid URL" );
        exit(0);
    }

    printf( "Here's the URL name: %s\n", tmp );
    
    return 0;
}
Aia 1,977 Nearly a Posting Maven

opt_httphost = argv[0] + 7; //+ 7 removes http:// Nope, argv[0] is a pointer to the beginning of the string that hold the name of the program being execute.

Given char *opt_httphost; : opt_httphost = argv[1] + 7; might put you at the beginning of the name address as long as you entered an URL as an argument.

Aia 1,977 Nearly a Posting Maven

And how should I check if string is palindrome. I just need some hints
thanks

Searching...

Aia 1,977 Nearly a Posting Maven

sscanf(line,"%3f2", &limit); remove red part scanf("%3d2", &x); do same here. printf("%3f2\n", a[n]); substitute for %.2f\n

Aia 1,977 Nearly a Posting Maven

Make the prototype: void PrintString(char **pArray) add an extra *

Call the function as: PrintString(*array); remove the *


Display each subscript of the pointer: printf("%d - %5s", i, pArray[i] ); add the individual pointer subscript

Sh13 commented: thanks +1
Aia 1,977 Nearly a Posting Maven

Then, the problem is that fscanf() is not been successful converting the input into floats.
In fact I can see another err: fscanf(ifp, "%f", &array[i].miles); fscanf() needs to have an address to store the conversion, you are not giving it that by missing the &
It's always a good practice to check the return of functions.
This is the return for it:
On success, the function returns the number of items succesfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned.

Aia 1,977 Nearly a Posting Maven

Did you initialized miles before starting to add to it?

Funny part: fscanf(ifp, "%f", array[i].miles); array.miles is the field of a structure array element. miles += array[i]; array is an element of an array, hopefully float or double.

Aia 1,977 Nearly a Posting Maven

>If you're already validating the string, sscanf is overkill.
Would you mind to elaborate in what way this would be overkill?

#include <stdio.h>

int main ( int argc, char *argv[] ) {
    int integer =  0;

    if ( argc > 1 ) {
        if ( sscanf( argv[1], "%d", &integer ) == 1 ) {
           <snip>
        }
        else {
           <snip>
        }
    }
    <snip>
    return 0;
}
Aia 1,977 Nearly a Posting Maven

value=(int)argv[1]; That will not give you what you want. argv[1] is a string in the best case.

Validate that the user entered an argument at the command line. Then use sscanf() to read that string into an int previously declared.

if ( sscanf( argv[1], "%d", &integer ) == 1 )
{
     printf( "%d\n", integer );
}
Aia 1,977 Nearly a Posting Maven

What do you mean to the public, like software companies, or individual people? Do they have to pay?

I was joking lemichelle. Hopefully my second post clears that.


Compiler, linker and library are three distinctive concepts. At times people referrers to them as a group with the loose term of compiler. The compiler mission is to make those written human code into binary code. The libraries are pieces of binary code which do some specify work, and the linker mission is to join all this together with the program you want to create.

Aia 1,977 Nearly a Posting Maven

>5. Where do all the function libraries come from? Did someone just create them and give them away?

Now a bit more serious.
What most people call compiler comes with a set of libraries, which are pieces of software in binary code. Of course someone needed to write and compile that code before hand.
You can find compiler/linker/libraries done by programmers, that do not mind to release to the public, all this work for no monetary compensation. But certainly, there are plenty of compiler/linker/libraries in the market for purchase. And what do you buy? The right to use it.

"Link Editor" might be the name of a software program that do something completely different that what the linker in compiling is suppose to do.

Aia 1,977 Nearly a Posting Maven

>5. Where do all the function libraries come from?
From the supermarket like potatoes and hamburger meat. Everyone does know that, doesn't it?

>Did someone just create them and give them away?
Nope, "The Library of Congress" issues license every year for the public to use those libraries, that's why you need to use the "Link Editor", which it checks that you have the right license in your program.

Aia 1,977 Nearly a Posting Maven

thanks jephtlah.i try to run ur code but it seems like got some problem.kindly help me again.

#include <stdio.h>
#include <string.h>
#include<ctype.h>
int letterValue(char letter);

int main(char *roman)
{
    int arabic = 0, tmp;
    char *str_p  = roman;
    
    while(*str_p)
    {
        tmp = letterValue(*str_p);
        if (letterValue(*++str_p) > tmp)
            arabic -= tmp;
        else
            arabic += tmp;
    }
    return arabic;
}
    
int letterValue(char letter)
{
    if (toupper(letter) == 'I') return 1;
    if (toupper(letter) == 'V') return 5;
    if (toupper(letter) == 'X') return 10;
    if (toupper(letter) == 'L') return 50;
    if (toupper(letter) == 'C') return 100;
    if (toupper(letter) == 'D') return 500;
    if (toupper(letter) == 'M') return 1000;
    
}

when i compile this code by click F7, dun have problem.
but once i click F5, it cannot run normally .and a box come out say that my exe file stop working.can u help me to check it ?

Heavens! Are you understanding the basics?
main can accept an int as the first parameter, and array of pointers as the second. But not a string pointer. Those are supposed to be functions outside main.

Aia 1,977 Nearly a Posting Maven

Perhaps is best if you work in small portions of what you intend to do; testing that you understand the principle first in an isolated state.

e.g.

void readinput(char english[])
{
	int count=0;
	char c;
	while((c=getchar())!='\n')
	{
		english[count]=c;
		++count;
	}
	return;
}

Consider:
The while loop will keep copying characters from stdin until encounters a new line.
What would happen if the newline is not reached before 80 times?

Continue considering:
The while loop has successfully reached a newline before it runs out of space for english.
Still english is not a string, since the '\0' ( string terminator ) hasn't be added to it.

jephthah commented: you're so much nicer than everyone else here :-) +1
Aia 1,977 Nearly a Posting Maven

>If it's the former I'll write it off as more classroom silliness. If it's the latter, I'll need to be on the lookout for macho code.

Oh, never saw it under that light. Always I have favored pointer notation when dealing with string pointers, if for any other reason that to make a feeble attempt for distinction between pointer and array.

>I'll need to be on the lookout for macho code.
Can't help but draw a parallel thought of six plus feet men making hulk poses for just placing a ball inside an over-sized metal ring.

Aia 1,977 Nearly a Posting Maven

>*(array + count) = ch ;
Just out of curiosity, why add the unnecessary complexity of pointer notation here?

Is it really that much complex from array[count] that it would warrant wondering?
Separate question:
Doesn't the compiler default to substitute array notation for pointer notation?

Aia 1,977 Nearly a Posting Maven

> Does anyone know the right method to terminate a string by the way?
Right method depends of what you are doing.

current[strlen( a ) + 1] = '\0';
current[ x+1 ] = '\0';
Aia 1,977 Nearly a Posting Maven
typedef struct
{
	int id;		//מספר הזהות של הסטודנט
	char full_name[LEN];		//שם ושם משפחה
    	struct
	{
		unsigned sem_a;		//ממוצע הציונים בסמסטר ראשון
		unsigned sem_b;		//ממוצע הציונים בסמסטר שני
	}grades;					//משתנה של ציונים מטיפוס של מבנה
}Student;

I believe you can benefit of reading this conversation. Click here
Nevertheless:

Student A[]={
		{10,"   SasonSasoniBenSason   ", { 100,100 } },
		{5,"    Pinokio    ", { 70,90 } },
		{20,"       JohnRambo ", { 50,87 } },
		{3,"Elvis", { 3,77 } },
		{50," JamesBond", { 17,1 } },
		{40,"BillGates", { 91,8 } }
	};

That's how you need to initialized grades inside Student A.

char first; 
char second;
void write_2_file( char first) /* first is passed without been initialized with meaningful value */
void coping(char first, char second) /* first and second are still not initialized with meaningful values */
int min_index ( int saveid[], int skip[], size_t n )
int min = min_index ( saveid, skip, 6 );  /* passing wrong saveid argument */

In fact you are passing wrong arguments in:

fscanf(f, "%d %s %u %u", &saveid[j],&savename[j],&savegrd[j],&saveavg[j]);
fprintf (to_f, "%d %s %u %u\n", saveid[min], &savename[min], savegrd[min], saveavg[min] );

main can not be void. Always returns an int.
fflush( stdin ) is incorrect as well. You can use fflush( stdout ), but fflush( stdin ) is in the land of undefined behavior.

while ((!feof(f)) && (j<6))

feof should never been used as the condition to exit a loop. It will loop at the end one …

Aia 1,977 Nearly a Posting Maven

>I don't understand what's wrong with assigning the value 0.1 to a float variable .

There's nothing wrong with it, the compiler is warning you that you are trying to assign a double to a float.
A literal 0.1 is a double in your compiler.
Do a test. Add these printf(s) to your snippet.

printf( "sizeof of 0.1 = %d bytes\n", sizeof( 0.1 ) );
printf( "sizeof of float = %d bytes\n", sizeof( float ) );

The result will be clear to you.

[Edit]: Some extra.

In fact even

if( a <= 0.1 )

will evaluate to FALSE because float != double. However

if( a <= ( float ) 0.1 )

will evaluate to TRUE

Eko commented: Very helpful +2
Aia 1,977 Nearly a Posting Maven

The following can also be done .. it does not involve strcpy() or arrays,
instead it uses a single pointer (real_out_ptr)

I would not suggest the use of pointers until array of chars are understood.

Aia 1,977 Nearly a Posting Maven

As soon as the block ( between the {} or single statement in the if/else control flow ) is executed the string disappears.
I suppose you want something like:

#include <string.h> /* for strcpy function */
char real_out[20] = { '\0' }; /* array declared outside the if/elses */
int output_type=1; /* you are missing semicolon */
if (output_type==1)
	strcpy( real_out, "binary" ); /* use of strcpy function */
else if (output_type==2)
	strcpy( real_out, "octal" );
else if (output_type==3)
	strcpy( real_out, "decimal" );
else
	strcpy( real_out, "This REALLY shouldn't have happened.\n" );

char real_out=[6]"octal"; char real_out[6] = "octal";
char[20]real_out="This REALLY shouldn't have happened.\n"; char real_out[20] = "....";
Watch how you define the arrays.

Aia 1,977 Nearly a Posting Maven

I doubt you since you are a n00b. ^
|:)

A simple "Thank you!" would have suffice.

Aia 1,977 Nearly a Posting Maven

Maybe this will help

Aia 1,977 Nearly a Posting Maven

>sort_date(struct_acc Acc[], int n);//Here Is Where the error is??
That should be a function call, however you are making it like if it were a prototype of the function sort_date.

Aia 1,977 Nearly a Posting Maven

A segmentation fault occurs when a program tries to access memory location that is not allow to play with.

My guess is that your char* is pointing to some wrong memory location. Maybe you haven't initialized to point to a string.

Aia 1,977 Nearly a Posting Maven

Did you wonder how come Ancient Dragon's code post looks so nice and your post is all scattered over, and hard to read?
Please read.

Aia 1,977 Nearly a Posting Maven

fscanf() would read from the same line and will read any data according to the % format you give it.
e.g

fscanf( file, "%s%d", stringArray, &digit );

will scand a line in the opened file and will try to read a string which will store in stringArray, and following it will try to read an integer; storing it in digit. After that it will return how many items was successful in reading or EOF if it failed. Remember everything from one line alone.

fgets() works differently.
e.g

fgets( string, totalsize, file );

will start reading from file until it reaches the totalsize less one for the '\0' terminator, or encounters a newline '\n' or EOF end of file, whichever is first of these. Upon completion it will return a NULL pointer if the EOF was reached and nothing was read, or an error occurred; if it was successful it returns a pointer to string changed with what it was read.

Suppose you have these words in a file:
Jiminy Cricket
And you want to read it into char name[12]; and char lastname[12];
if you call

fgets( name, sizeof name, file );
fgets( lastname, sizeof lastname, file );

What do you think it will produce?

char name[12] = "Jiminy Cric"; /* count the characters */
char lastname[12] = "ket\n";

I hope this will help telling you what's happening in your code.
Did you take a look at why feof() is

Aia 1,977 Nearly a Posting Maven

Quick and dirty way of getting an integer from user.

/*
 * =====================================
 *
 *    Description: show how sscanf works 
 *
 *        Version:  1.0
 *        Created:  2/12/2008 5:15:26 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Aia 
 *        Company:  AiaONE
 *
 * =====================================
 */

#include <stdio.h>

int main( void )
{
	char integer[13];
	int result = 0; /* default value */

	printf( "Enter an integer: " );
	fflush( stdout );

	if( fgets( integer, sizeof integer, stdin ) )
	{
		if ( sscanf( integer, "%d", &result ) < 1 )
		{
			/* sscanf failed, going with default */
			puts( "Sorry not integer entered" );
		}
	}	
	printf( "result = %d\n", result );

	getchar(); /* pause if less than 13 characters were entered */
	return 0;
}
Aia 1,977 Nearly a Posting Maven

on that note using fgets() if I was reading in ints,chars etc from the same file. would i need to use fgets(name,sizeof name,stdin);
fgets(amount,sizeof amount,stdin); etc?

fgets accepts as parameters an array of char, the length of that array ( how many chars can read into it without going over the space set apart for it ), and the file handle from where it needs to read; in this case the standard input buffer stream, but it can be any file you have opened for reading.
It doesn't accept integers. However integer can be read as strings and then converted by another function like sscanf() ( notice the extra s which stand for string ).

Aia 1,977 Nearly a Posting Maven

cus = malloc(sizeof(struct customer));
Only one time memory is set apart. In essence cus[0], because int i is set to 0;
The program hits the loop and makes use of that memory via cus[0], but in the next cycle it tries to make use of cus[1] which chuck of memory doesn't exist.
Remember to free that malloc-ed memory after you're done with it.
scanf( "%s", &name ); doesn't need the &. Is already a pointer to the first element of the string.
However I would stop any use of scanf() when you want to read a string.
fgets( name, sizeof name, stdin ) is a much safer way.

Aia 1,977 Nearly a Posting Maven

quickly came across another problem I can only read in one customer from the file it will onnly take in the first person in the file?

Post the modified version of your code.

hallinan commented: always helpful!! +1
Aia 1,977 Nearly a Posting Maven

It's never a good idea to control the exit of a loop by the use of the feof() function.
For some clear explanation, click here.
And since your are there, take a look at scanf for reading strings, as well. You won't regretted.

Aia 1,977 Nearly a Posting Maven

*cus[max]; This declares 100 pointers of type customer, but you haven't point them to any memory, therefore you cannot use them in the fscanf() call.
Malloc can set apart memory of type structure customer and you can access it via cus pointers.

Aia 1,977 Nearly a Posting Maven

Stick with one forum. You are been helped over here.

Aia 1,977 Nearly a Posting Maven

It is not my place to lecture you here, however it is annoying to the people that helps in diverse forums to see the same person asking the same question across boards, especially when you could have continued inquiring about what you didn't understand at the first post.
I am going to point to you to the same code sample, in case you missed it. Look inside for these lines of code:

if (!CreateDirectory(argv[1], NULL))

That's to make the directory

if (CopyFile(FileData.cFileName, szNewPath, FALSE))

That's to copy the file.

>>Also isnt that code for the win api GUI thing? Would it be applicable to console based programs?

These are Windows API functions, that allow you to do programming in the MS Windows Operating System as efficiently as the designers of the system intended. There's some ways that you could achieve the same result using standard C functions, but the API will do it more efficiently. Or that's the idea behind. You can program for a GUI or for a shell command line window.

Aia 1,977 Nearly a Posting Maven

What part did you not understand of the answer over here?

Aia 1,977 Nearly a Posting Maven

Go to statements go like this:

/* create the label */
    ins:
/* then call the goto */
    goto ins;

Substitute every goto <label>: that you have for <label>: or goto <label>; depending on if is a call or a label.
BTW. What a fine example of why goto shouldn't be used. You have a "messed up" code that doesn't even work, but because there's so many jumps with goto I am not inclined to find out why it doesn't work.

Aia 1,977 Nearly a Posting Maven

if(!(a%10))
but what is not (a%10)?

if( !( a % 10 ) ) What's the programmer trying to achieve here?
Is looking for when the result of the operation a % 10 would be 0, however 0 inside an if statement will never execute since in C, 0 is considerate FALSE. Hence the ! added inside the if() to force its execution.

With this information in hand, think about the other examples you're querying about.

Aia 1,977 Nearly a Posting Maven

My point is, what makes you think the OP hasn't already a modern compiler installed.

Thinking? No. No assumptions in my part. Just two rhetoric questions based on this comment;

Hi :) I am using TurboC++ IDE 3.0.

and on this one.

I agree, but its unfortunate that few schools like ours still insist on "riding a horse". And i have no choice but do what i am supposed to.

Aia 1,977 Nearly a Posting Maven

He needs to write a program using BGI graphics for school.

You earned yourself an A- for writing it "in your own words".

He never said anything about not using a modern compiler in his free time.

No. Never, she/he neither said anything about if she/he prefers a "burrito" from Taco Bell or a "Big Mac" from MacDonald's. What's your point?
Only a student sees "free time" as a real concept.

Aia 1,977 Nearly a Posting Maven

I agree, but its unfortunate that few schools like ours still insist on "riding a horse". And i have no choice but do what i am supposed to ...

"Don't let school get in the way of your education." ~Samuel Langhorne Clemens~
What would prevent you from installing a modern compiler and trying to learn by your own, if that is what's required for you to learn correctly? Giving to Cesar what's Cesar's and to you what you need in order to succeed?

Aia 1,977 Nearly a Posting Maven

Concerning this:

gets (argv);

NEVER, ever, ever, EVER use gets. Forget that exist.

You did not understand what Ancient Dragon was telling you.
argv is an array of pointers to strings, where input could be used at the start of the program in command line.
If you want to obtain input from user after the program is running, use the function fgets() to read it into an array of chars. Then separate the words, flags or commands entered by reading up to the space for each one.

Aia 1,977 Nearly a Posting Maven
void modifyString(char *pstr) {
    char *str = pstr;
    // Make changes to str ...
}

void doSomething() {
    char str[] = "Hello World";
    modifyString(str);
}
Aia 1,977 Nearly a Posting Maven

OMG this is the problem i get while use the functions
warning C4013: 'strlen' undefined; assuming extern returning int

strlen() is defined in the header file string.h. #include <string.h>

Aia 1,977 Nearly a Posting Maven

What is the problem here?

I am running linux and gcc 4.1.

You're compiler doesn't know what O_RDONLY is.
Did you include fcntl.h?

Aia 1,977 Nearly a Posting Maven

Hi ,

The source is working but i do not understand how can work in line 68: the function without giving arguments.
Thanks for reading.

int (*compare)(char *s1, char *s2);

This is a pointer to a function that would have two parameters strings.

int reverse(char *p1, char *p2); 
int alpha(char *p1, char *p2);

Either of these two functions could be candidates for the compare pointer, since both of these functions accepts the same parameters and returns the same; an integer, just like the pointer to function declaration.

Now to the initialization of the pointer.
it could be like this:
compare = reverse;
or it could be like:
compare = alpha;
Both of these statements initialize compare to point to any of these functions.
However the statement:

compare = (sort_type) ? reverse : alpha;

initializes to one of them according to sort_type which is an int. If is 0 or false compare will point to alpha; if is more than a 0 or true; compare will point to reverse.

Aia 1,977 Nearly a Posting Maven
for(fill = 0; fill < (m-1); ++fill)
   {
     if(atomic_num[index_of_min] <= atomic_num[fill])
     {
     temp = atomic_num[index_of_min];
     atomic_num[index_of_min] = atomic_num[fill];
     atomic_num[fill] = temp;
     }
    ++index_of_min;
   }

  
   for(j = 0; j < (m-1); j++)
      fprintf(outp,"%d\n", atomic_num[j]);

It looks to me that you were trying to implement a bubble sort.
For that you need two index variables and two loops.

/* indexes for loops */
    int a, b;

    /* How many elements atomic_num has? */
    int size = sizeof atomic_num / sizeof ( int );

    /* temporal storage */
    int temp;


    for ( a = 0; a < size - 1; a++ )
    {
        for ( b = a + 1; b < size; b++ )
	{
	    if ( atomic_num[a] > atomic_num[b] )
            {
		temp = atomic_num[a];
		atomic_num[a] = atomic_num[b];
		atomic_num[b] = temp;
	    }
	}
	/* printf( "%d\n", atomic_num[a] ); uncomment for displaying */
    }
Aia 1,977 Nearly a Posting Maven
/* void is not good*/ int main()
{
   /* clrscr(); remove this */
  int r, ones=0, zeroes=0;
  long int n;
  printf("Enter A Binary Number ");
  fflush( stdout ); /* use when you are not terminating a printf with a \n */
  scanf("%ld", &n); /* n is a long integer, so you need l */
  while(n!=0)
  {
    r=n%10;
    if(r==1)
      ones++;
    if(r==0)
      zeroes++;
    n=n/10;
  }
  printf("\nNumber of ones are %d", ones);
  printf("\nNumber of zeroes are %d", zeroes);

  /* getch(); is not portable use: */
  getchar(); /* in this case you need to call getchar() twice */

 /* add */ 
  return 0;
}

Try now.