Advertisement

MORE C help needed! :)

Started by June 27, 2000 11:13 AM
15 comments, last by CoiN 24 years, 5 months ago
May aswell get another question in here

Should this piece of code work?

    void main(void){     char *p;     scanf ("%s", p);     printf ("%s", p);}    


Im sure i remember using character pointers to hold strings this way, but my mind has gone blank today


why not just use cin and cout
it makes the code look so much better and easier to read
you dont have to make all those function calls.......i know using cin and cout really do call functions but this is hidden from you and is easy to implement
    #include <iostream.h>void main(){    double average[10];    char names[10][50];    for (int count=0; count < 10; count++)    {        cout << "Enter name " << count << endl;        cin >> names[count];        cout << "Enter average " << count << endl;        cin >> average[count];    }    for (int i=0; i<10; i++)    {        cout << names<i> << "    " << average[i] << endl;    }    




"Now go away or I shall taunt you a second time"
- Monty Python and the Holy Grail
themGames Productions

Advertisement
quote:
Should this piece of code work?

void main(void)
{
char *p;
scanf ("%s", p);
printf ("%s", p);
}


No. p is a pointer to a character or character array, but it isn''t initialized, so it points to nothing. You''ll get an access error. You need to add:

p = new char[50];

in order to get it to work. Also, after you''ve used p (i.e. at the end of the program), you should delete it:

delete [] p;


CoiN, to answer your question, yes, you CAN do that, but that doesn''t mean it''s correct. You write to random memory, and most of the time that will cause a GPF if you''re working under Windows, if you''re in DOS, you might not get any errors, but the program is going to crash someone''s computer (including yours) if it unexpectedly write to a memory location it''s not supposed to... In order to fix the problem you have to allocate enough memory to hold your array of chars (string). Other than that, the code is going to work, especially in DOS...

Hope this helps!

..-=ViKtOr=-..
Thanks, Ive had a really funny day forgetting lotsa stuff

I''ll just stick to using the standard array of characters
Oh, and that should be

int main();

Advertisement
rrrrrright

This topic is closed to new replies.

Advertisement