Adak 419 Nearly a Posting Virtuoso

Forget your code. Take a pencil and paper, and draw your array of 4 x 4 (or 2 x 2), whatever size you need. Make it simple as you need it to be.

Now, look at the paper from above, paper flat on the table or desk. Now slowly turn the paper 90° to the right. Repeat that until you have noted the 1st position of every element of the array, and it's last value, after the array is rotated.

<< THAT'S how you learn to solve a problem. >>

If you use a different value for every element of the array, it may help you.

Write down the equation that solves the change in position for any element, after the array has been rotated, given it's starting position. It's simple arithmetic, so no trig or calc is necessary, here.

Doing it this way, you WILL LEARN and remember, how this works, for a very long time. If I just told you, you'd forget it inside of a week.

And have fun, because this is a fun exercise. ;)

Adak 419 Nearly a Posting Virtuoso

What I'd recommend is DON'T write it up to the line printer, directly.

Instead, print it to the screen, once you know the top left and bottom right of the printable area of your printer.
Enumerate your rows and columns:

XX1234567890123456789012345678901234567890  << row just before the first printable row
X1.......................................X << First printable row
X2.......................................X
X3.......................................X
X4.......................................X << row numbers
X5.......................................X
X6.......................................X
X7.......................................X
X8.......................................X
X9.......................................X
10.......................................X
11.......................................X
12.......................................X
13.......................................X
14.......................................X
15.......................................X << Last printable row
XX12345678901234567890123456789012345678901234567890 << Column enumeration numbers

X or a digit = a position that your printer can't print in.

Naturally, you want to set your printer up for the widest and tallest print area, that you can.

When it looks right, then print it. Probably by writing it to a text file,and then printing it with Linux, for right now. How many of these sheets do you have to print up?

Once you have the pages printed to file, you can easily print them up with Linux, using Ubuntu. I'm not sure how you print directly in Linux, but I'm sure the Ubuntu Forum (which is VERY active and good), can tell us. :)

BlackJavaBean commented: Very well written and to the point. Extremely helpful! +2
Adak 419 Nearly a Posting Virtuoso

Welcome to the forum, Dharma. :)

Two suggestions for your study in C:

1) for technical reasons, C should always have an int return from main. The correct format for main in these programs would be:

int main(void)

with

return 0; at the end of main.

I know void is taught sometimes, and shown in books, but that is wrong, and support for it may not continue in the future.

2) variable names like i,j,k,a,n, etc., are all good, but in this program, and in your programs in the future, it's a huge help to use descriptive variable names like row, rowNum, column or columnNum, etc. We all "get" and use i and j quite commonly, but the rest of those names - well, they could be improved.

Right now, I'm re-writing a program I wrote some years back (expanding it and upgrading it to 64 bit format), and it's a BIG help to have descriptive names for most of the variables where the purpose of it is not easily remembered years later.

arindam31 commented: That was great suggestion.....Ill try to follow these from now on... +0
Adak 419 Nearly a Posting Virtuoso

A far better choice: Pelles C - free (only for Windows), but 32 or 64 bit, and unlike Turbo C (which I dearly loved btw), it's up to date, including having it's own support forum.

Like Turbo C, it's intuitive to use, and has plenty of help. You'll love it, AND be WAY more up to date and able to program in Windows, etc.

Ancient Dragon commented: thanks for the link :) +36
Adak 419 Nearly a Posting Virtuoso

Use a good sized char array[100] or so, and fgets(array, sizeof(array), filePointer), to put one row of data into the char array.

Now, in a for loop from array[0] to array[strlen(array)], count up your spaces and add 1 - that is how many numbers you have in that row.

now malloc() memory for that size row, and sscanf() your numbers into the numbers array (which is a 2D dynamic array, of course, of type int).

The numbers array would be "ragged" in length on the high side, but save the maximum amount of memory, if that's what you want or need.

Personally, I'd use Walt's idea, simply because memory is plentiful. BTW, you could do this same type of thing with nodes, in a linked list.

t_man700 commented: Thank you for your response. I appreciate it! +1
Adak 419 Nearly a Posting Virtuoso

You have been given the same answers in two different C forums, I hope that's enough cross posting on this subject.

Adak 419 Nearly a Posting Virtuoso

In C, you read a text file line by line, using

fgets(charArrayName, sizeof(charArrayName), filePointerName);

Which will automatically insert the whole line of text, into your char array, including the newline (and the end of string char: '\0', after that. (If room allows).

while((fgets(charArrayName, sizeof(charArrayName), filePointerName)) != NULL) {
  //your code here

}

Is a standard idiom in C to read every row of text in the file.

Railroad theme, I see. ;)

codeyy commented: very helpful +2
Adak 419 Nearly a Posting Virtuoso

Edit: this seemed to work OK, in my very limited testing.

fp is the file pointer, ch is a char, and the other variables are int's. ctype.h was included, of course.

while((ch=getc(fp)) != EOF) {
    putchar(ch);
    if((isalpha(ch)) && (inword==0)) {
      inword=1;
      wordcount++;
    }
    else if(!isalpha(ch)) { //isalpha(ch)==0
      inword=0;
    }
  }
  fclose(fp);
  printf("\n I counted %d words in that file\n", wordcount);

Give this a try, and if no luck, post back, but I think you'll get it from this.

Adak 419 Nearly a Posting Virtuoso

Not yet - that's the same logic as before, using different variables. :(

in the header file ctype.h, we have functions to test what kind of char it is. I'd use two of them, so include <ctype.h> at the top of your program.

Those two are ispunct() (is it a punctuation, and isalpha(), is it a regular alphanumberic char (letter or number)?

So the logic will be (approximately):

if((inword  equals 0) and (isalpha(char being checked))) { //
  inword = 1
  wordcount increments by one
}
/* handles last word in a row which has no space after it. */
else if(char equals ' ' or !isalpha(char being checked)) {
  inword = 0
}

May be more logic needed, but not much. It's been a long time since I coded one up. Give this a try, and post back up and I'll study it more.

Adak 419 Nearly a Posting Virtuoso

Instead of the simple if(char == space) logic, (which obviously can't handle multiple spaces), how about this.

inword = 0; changes to inword=1 when you find a word. When you leave a word, it goes back to 0.

First letter you run across, you set it to 1, and increment word counter. When you run into the first space, you set it to 0, and do not increment word count any more, until you run into the next letter.

You need to add some logic to handle things like the last word in a sentence, at the end of a file, etc.

Adak 419 Nearly a Posting Virtuoso

If you want any respect on a programming forum, I'd change your forum handle.

Outside links to "alice", won't go over well, either.

Adak 419 Nearly a Posting Virtuoso

A couple big time savers:

1) You only need to check a number up to (and including) the square root of that number. If the number is prime at that time, then it's prime.

2) increment your loop by 2 for the numbers to be checked for primeness. Even numbers can never be prime if they are higher than 2.

You can read up on the Sieve of Eratosthenes at Wikipedia.

Adak 419 Nearly a Posting Virtuoso

This is THE most complicated, and most verbose flood fill function, (because that's all it should be - one function), I've ever seen.

You've made a serious error in how you program:

1) You've written a lot of code, but obviously didn't do any testing along the way.

2) So the bugs are likely to be anywhere.

That's a very poor methodology. What you should have done is test each function as you went along, that it was accurate and kept the flow of the program, going as is needed.

The first thing I'd do if it were me, would be to goto Wikipedia and read up on "Flood Fill" algorithms. Then I'd choose one of those that I liked, and code it up. Check your compiler, also. It may have an extension expressly for this purpose. Note that flood fill may mean filling in just one color, or one area, and not the entire picture.

I don't want to sound negative, because the work that went into this is substantial. I don't understand WHY someone would do it this way.

Beyond accuracy and run time efficiency, one of the major goals of your programs is clarity. There WILL come a time that you'll want to adapt part of this code, for use in another program, or to extend what this program already does. See what I mean? Even if you get it to work fine, it's real value is greatly diminished.

Adak 419 Nearly a Posting Virtuoso

I'm just curious - what would you guess that "lib" is short for? ;)

I mean really, take a guess!

When you're ready for a bitchin' C IDE and compiler, FREE! and includes support for conio.h (like Turbo C), but works on 32 and 64 bit cpu's and OS's, like Windows XP, Windows 7, Windows Vista, and Linux:

Pelles C! IDE, HELP files, HELP forum, and no bloat! ;)

http://smorgasbordet.com/pellesc/

I'm been using Turbo C since ver. 1.01 (and still do for small puzzles and stuff), and disliked the horrid interface of MSVC and it's bloat. But Pelles C is WONDERFUL stuff.

You try this for 30 days, and I guarantee you will be glad you did.

jonsca commented: Make this a sticky!! +6
Adak 419 Nearly a Posting Virtuoso

It's easier if you create the array in the calling function, then pass it into the called function as a parameter. Upon return from the called function, the array is still valid, and has the data you want in it.

You can do it the other way, but it's more work.

Splam Bub commented: Nice and helpful. +0
Adak 419 Nearly a Posting Virtuoso

Sonuja, we aren't interested in "providing examples" and explanations for SQL access.

What we do is help you with your C code, if we can. You need to put in the work to first, get a start on your code. Then post it, and tell us what's gone wrong or what has you stumped.

There are a LOT of SQL access examples on Google, if you want to study them.

Adak 419 Nearly a Posting Virtuoso

For encrypting, N would be a number that was defined or declared a const, earlier in the program. K I'm not sure of, but I'll hazard a guess it's a prime number chosen by the algorithm, on this run. Might be a hash value, also.

Key[] is the index array used to help encode (along with i and some simple arithmetic), the plain text (word[]), into encrypted text - which is being put into the array w[].

You need a bit more info on N and k, and on the values put into key[], before this while loop started.

What algorithm is this taken from?

This is not difficult code, but you need a bit more info to do it as it was intended to be done.

Adak 419 Nearly a Posting Virtuoso

Ancient Dragon already laid out how to read a file, if you want to read the entire file, row by row:

while( fgets(buf,sizeof(buf),in) // read the rest of the file
{
   //your other code in here, will strcpy() buff array
   //into another string or string array. First, you could
   //remove all the comma's in the string, very easily.
   //One of the beautiful things about using fgets().
}

You'll be doing yourself a favor to make a note of the above, and get really familiar with it. Very useful indeed.

I would use sscanf() to get the column you want's data, out of the row. I don't really prefer strtok(), for you, since it modifies the string, as it's working.

Look at that! I already gave you this same advice. :(

No offense, but you need to either work on reading or studying the replies you're being given, in the forum. You're wasting people's time, as it is. Here's my previous reply to you, in your other thread on this assignment:

make a char buff[100] array, to hold one line of text
make a float data[SIZE][COLS]; //fit your sizes for rows and columns.Leave room for 
end of string char and newline char, in your column number  
still have index[SIZE];

while((fgets(buff, sizeof(buff), filePointerName)) != NULL) {
  ok = sscanf(buff, "%*s %*s %f", floats[i]; //skip the 2 leading strings, store the float number into an array of floats
  if(ok > 0) {
    strcpy(data[i], buff);//copy buff string (including float), …
Adak 419 Nearly a Posting Virtuoso

VS has posted 13 times - past due for the OP to start using code tags.

Deducting rep points for using code tags, instead of the (more concise) icode tags, is a bit too much control, imo.

WaltP commented: Agreed. If you like CODE rather than ICODE, go for it... +15
Adak 419 Nearly a Posting Virtuoso

Break it down into a few big steps (amid smaller one's):

1) Get your connect 4 program using one thread, working PERFECTLY. No crashes, no illegal moves, etc.

It's difficult to debug a multi-threaded program, so get the single threaded version of your code, working really spot on.

2) Now work your single-threaded code, into a multi-threaded program. Imo, let every thread work independently of the other, as much as possible.

3) Now polish it up, and test it out, REALLY well. You may find bugs long after you thought they were all gone.

There is all kinds of example code for both multi-threading and connect 4 on the net, so get in there and study up. This will take more time than you expect, so don't put it off.

Adak 419 Nearly a Posting Virtuoso

My eyeballs get tired just studying your code. ;)

Instead of two arrays to convert letters from one case to the other, why not use toupper() or tolower() (part of ctype.h)? Another easy way would be to simply use the ascii values. Since there is a constant difference of 32 between the uppercase letter and it's lowercase equivalent, we can use:

ch += 32; //to change char ch from uppercase to lowercase
ch -= 32; //lowercase to uppercase

Both the above work ONLY for letters, and ONLY if your system uses ASCII or other character values with this 32 offset (most do). Try it on your system.

You're using u and y for for loop iterators - please don't. Use the standard idiom of i and j and k if you need it. When you have no comments in your code, it's just so much easier if you use standard C idiom's.

You should be using strtoi, atoi or sscanf() to take your string digits, and convert them into a (real) number. It's so easy.

I'm all for repentance from sin, but go to confession, instead of beating yourself up with C. ;)

Be as simple and concise and as clear, as you can be in your algorithm and code. You'll be glad you did.

Edit: set your editor up to insert 3-5 spaces, instead of full tabs, when you hit the tab key. Your indentation is so great, that your …

zetologos commented: thanks for useful advice +1
Adak 419 Nearly a Posting Virtuoso

I believe you are laboring under a very poor concept here. You do NOT NOT NOT want to mess with the "inner" workings of a proven cryptology program.

It works -- leave it alone.;)

Treat each part of it (encryption and decryption), as "black boxes", and code up function logic around them (like a wrapper around a sandwich - it doesn't disturb the contents of the sandwich in any way).

The NIST studied several candidates for their new crypto program, and have put a lot of info on their relative performance, into a PDF you can download from their website.

With that in mind, I don't see your problem: you have the code you need for the crypto program, except how you want to combine the two functions, into one.

I answered that question: you use a parameter value that you will pass when you call the crypto function. That will decide whether the text you're also passing (or file), will be encrypted, or decrypted.

Good crypto programs are fine pieces of logic, and have to be extensively (very extensively) worked out by the creators, and tested. If you change just one piece of the "inner" logic, you may easily ruin it, AND you probably won't know it without a huge amount of testing, by experts in the field.

In conclusion, don't mess with the inner workings of the crypto program. Use it, and make any "wrapper" type handling function for it, that …

Adak 419 Nearly a Posting Virtuoso

Let's be clear - you can NOT run a graphics program from Turbo C, in your compiler. It's not a matter of C, it's a matter of support for and inclusion of the graphics.h file. Your compiler doesn't have it, and nobody else uses Turbo C's graphics header files (that I know of, and I've been using Turbo C for since the early 1990's).

You will have to use a graphics library or header, that's compatible with your compiler. Or download Turbo C and use it (from the Borland legacy program site).

Adak 419 Nearly a Posting Virtuoso

So post your code (and do paste it between the code tags you get by clicking on the icon in the editor), and tell us what has you stumped. [/B][code ] icon in the editor), and tell us what has you stumped.

Adak 419 Nearly a Posting Virtuoso

Turbo C, as was mentioned just above, has a very unique graphics ability. You can't duplicate it in another compiler, (in anything like a realistic amount of time and effort).

So you can use this clock code as something to study and learn from, but you can't fix those errors and run it, in graphics mode, without Turbo C.

My suggestion is to make a digital clock in a console window, first. Then work to understand the graphics that you need to use to display an analog clock, in a modern window, with modern graphics.

All in a timely manner, of course! ;)

Adak 419 Nearly a Posting Virtuoso

I know two verses of a song (in a function), but I need someone (another function), to tell me which one to start singing.

How could that be done?

Have you ever heard of PARAMETER City? Lovely place. Post up your map and bring your compass, and we'll get you there.

if(you want to visit the museum) (parameter type is 1, so encrypt)
  arrive on a Saturday (encrypt)
else
  arrive on a Monday for best room rates (decrypt)

I love the travel industry. ;)

Adak 419 Nearly a Posting Virtuoso

When you have several fields which all relate to the same object, you create a struct which will group the different fields (members of the struct), into one record (struct).

Then you use the dot member to access any member of the struct:

system.date
system.type
system.os
system.version

etc.

Which you will prototype right above main() so any function can make a local stuct for data it needs to work on.

struct system {
  char date1[10];
  char type[25];
  float version;
  int somevariableName;
  //etc.
}

When you want to get a bunch of these together into an array, you simply create an array of structs:

struct system systems[SIZE];

Structs are a great thing, but be aware that the compiler will add a small amount of padding for alignment purposes, and not every compiler will pad them the same. That makes portability a real issue. Same compiler on a different system, may have different padding. ;)

Of course, you can sort the data according to any member of the struct.

Adak 419 Nearly a Posting Virtuoso

The earlier posts are from 2009, so I doubt they will answer your questions.

You need to start a new thread with your problem, and let this one be buried, again. ;)

Adak 419 Nearly a Posting Virtuoso

Did you try SENDING the data at slower speed? ;)

I want you to brush up on your Win32 serial communications, here:
http://msdn.microsoft.com/en-us/library/ms810467

and be sure to download the sample program that is linked right below the top paragraphs.

Run that sample, and see if it runs OK. What I want to confirm is that:

1) your hardware is OK. If you're going from one computer's serial port to another's, you need a cross over cable - not a straight through serial cable.

2) A known good program, will run on your system, correctly.

If #1 and #2 are OK, then we know that the system and the cable/serial port, are working properly, and start narrowing down the suspects in your program.

Unfortunately, serial communication has changed hugely since DOS days, and while some serial programs will still work, others simply will not.

Adak 419 Nearly a Posting Virtuoso

Each student will typically be taking several courses each semester, so adding more classes into your student struct, would not be unreasonable.

Two other alternatives:

1) Add a classes struct, and nest it inside your student struct.

The one I like best is an array of char, where each class is listed by it's abbreviation (standardized), and it's course number: so BIO110 refers to Biology 110, PHY212 to Physics 212, etc.

Now every class has exactly 6 char's (maybe you want 7 or 8 for some schools), and by simple division, you easily have the number of classes, and finding any class within this string for a database, would be easy.

I believe you're working toward this, are you not?

Joey_Brown commented: Adak, youve gave me a great idea m8! Thank you +1
Adak 419 Nearly a Posting Virtuoso

Double your getchar()'s, and all will be well.

When you enter a char, you hit the the enter key, putting a newline ('\n') char into the keyboard stream (stdin). The first getchar() pulls off only the char you pressed BEFORE you hit enter, leaving the newline behind - and lets it get picked up by the next getchar().

You enter: 'A', but stdin has: 'A''\n', and that's your problem.

ch=getchar();
getchar();  //add this line

solves the problem.

Adak 419 Nearly a Posting Virtuoso

Makes sense it might do this, doesn't it?

First, it makes room for f[], then it makes room for g[]. Nothing in between is made, so it's quite probable that f[] is just beneath or above g[].

When you "walk" off the end of f[]'s boundary, what might you very well run into, except g[]?

Wouldn't be anything to rely on since it's totally undefined, but you can see how it might happen, just like that.

Now go program the right way. ;)

Adak 419 Nearly a Posting Virtuoso

Very interesting Brian, thanks for sharing! ;)

And welcome to the forum. :)

Adak 419 Nearly a Posting Virtuoso

Change your %f, %s, %s to %f%*c %s%*c %s

The %c handles the ',' char, and the * modifier in front of the c, should tell fscanf(), not to store the char.

fscanf(filePointerName, "%f%*c %s%*c %s ", &myFloatVariable, myString1, mySring2);
Adak 419 Nearly a Posting Virtuoso

Why not have the user input an integer, instead of a char, (as mentioned above), and use a do while loop, instead of a while loop? That will put the test for what the user entered, AFTER they have entered the loop, instead of right at the top of it.

(This can be done with a while loop, but the logic has to be changed. It's more intuitive to use a do while loop, for clarity.)

Adak 419 Nearly a Posting Virtuoso

Consider the number 123:

while number is greater than 0 
  one = 123 % 10
  number = number/10  //remove the digit in the one's place from the variable number.
loop

That's all there is to it. It peels off the digits, one by one, from the right hand side. Count the number of times it loops, if needed.

Adak 419 Nearly a Posting Virtuoso

First, dice IS plural - die is singular. There is no "dices".

Sure, you can check each char in the string, to see if it has only certain char's. A check function might look like this:

/* where 5 is the size of the input array. */

int checkStr(char input[5]) {
  int i, good=0; //assume input is not good
  char c;
  for(i=0;input[i]!='\0';i++) { //'\0'= end of string marker char
    c=input[i];
    if(c!='x' && c!='X' && c!='-')
      return good;
  }
  good=1; //if you reach here, then input must be good
  return good;
}
Adak 419 Nearly a Posting Virtuoso

Greater than 0, not less than:

while ((n = fread(buffer,1,sizeof buffer, original_pointer)) < 0)
moroccanplaya commented: explains stuff verywell, and he is one clever guy +1
Adak 419 Nearly a Posting Virtuoso

Go through the array twice:

First time, count the number of times each letter appears. That's easily done using logic like this:

for each row
  for each columm
    ascii[this letter's ascii value]++, coded like:
    ascii[myLetter]++;
  end for
end for

(a 256 element array of type int, will do nicely for ascii[].)

Now when complete, go through the ascii[] array, and find the largest values(s), and assign them to your maxLetter1, maxLetter2, etc., variables.

Then go back through your array, and mark out the letter which equal maxLetter1, or maxLetter1 and maxLetter2, etc.


Sounds like it would take a long time, but it doesn't because the small array easily fits in cache memory -- Zoom! ;)

Adak 419 Nearly a Posting Virtuoso

You try to enter float type data, into integer variables -- that won't work.

Change your data type to float or double, for everything that handles anything with a decimal point, and your computations should improve a lot. ;)

A big hint for troubleshooting programs like this:

You have a LOT of data to be input for each run of the program. That's a real slow-down, when you need to run the program several times, to fix bugs that remain.

To speed it up HUGELY, just // the left side of the scanf() lines of code, and add an assignment line with a typical value, instead. Not:

scanf("%f", &someFloatvariable);

//but

//scanf("%f", &someFloatvariable);
someFloatVariable = 88.15;

Now you can troubleshoot MUCH faster. ;)

You'll need to cut out the assignment line of code, later on, but in the meantime, you can really scoot on your troubleshooting.

Adak 419 Nearly a Posting Virtuoso

You can do this with just one pair of nested loops, but I like using two to simplify it.

The first pair of nested loops fills the char array a[][] with the correct values. The second pair of nested loops, prints them out.


Clear out the array, to just spaces:

char a[R][C];

//zero it out:
for(r=0;r<R;r++) 
  for(c=0;c<C;c++)
    a[r][c] = ' ';  //a space

Now the real loops in pseudo code:

for each col 
  for each row  //like turning the array 90 degrees counter clockwise
    if row < value in your occurrences array for col's value
      a[row][col] = '|'
    else if row == value in your occurrences arrary
      a[row][col = '^'
  end of for each row
end of for each col     

Now you're ready to print, but it has to be from the top down, so it will display with the higher values being higher up on the screen.

for r=R; r> -1; r--
  for c=0; c < C;c++ //still going upward on c, so it reads left to right
    print a[r][c];
  end of for c=0...
  putchar('\n'); //end of a row
end of for r=R...

And there you go. Add your footer lines, and anything you need along the vertical on the far left or right hand side, for the scale.

;)

Adak 419 Nearly a Posting Virtuoso

You need an outer "overall" loop (usually a for loop, let's say)

for(each number) {
   j=1;
   while(array[i] == array[i+j] { //because they're *sorted*
      ++j;
   }
   if(j > maxRepeats)
     mode = array[i];
}

That's to get you started, you may have one off errors in it -- it's very late here.

The key thing is, since the numbers are sorted, the repeating numbers, will be right next to each other. So a while or do while loop, is an intuitive way to do it.

Adak 419 Nearly a Posting Virtuoso

Add:

#include <limits.h>

Either use a

#define SIZE 12

macro, or get size this way:
size=sizeof(a)/sizeof(a[0];

You'll need that size of the array, I'll show you why.


This is NOT refined code - I believe this is best done recursively, but recursion
is hard to follow, without some experience with it.

for(i=0;i<size;i++) {
  //your main loop
  j=i+1;
  n=a[i];
  compress=0;
  while(a[j]==n && j<size) {
    compress++;
    a[j] = INT_MIN;
    ++j;
  }
  /*if you have a compression here
  increment i and set a[i] to compress+1
  and you need to shuffle the digits, down
  */
     //meet shuffle time ;)
    for(j=i+1;j<size;j++) {
      if(a[j] == INT_MIN) {  //found an element that needs to be overwritten 
        --size;              //reducing the effective size of the array by 1   
        for(k=j;k<size;k++) { //copying down the digits
          a[k] = a[k+1];
        }
        --j;                  //yup, tinkering
          
         //printf("\n Size = %d\n", size);
         //for(m=0;m<size;m++)
           //printf("a[%d]=%d ", m, a[m]);
      }
    }
  }//end if 

}//end for

Work with something along those lines, Joey.

Joey_Brown commented: gr8 guy !! +1
Adak 419 Nearly a Posting Virtuoso
# include <stdio.h>

void show(int (*)[3],int,int);

int main()
{
  int a[3][3]={1,2,3,
	       4,5,6,
	       7,8,9};

/* I would prefer the explicit:
  int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
note the doubled braces
*/
                

  show(a,3,3);
  return(0);
}
void show(int (*p)[3],int row,int col)
/*I would use:
void show(int p[3][3]) 
using the call 
show(a);

Which emphasizes at a glance (to me anyway), that it's a true 2D array
that is being referred to, here.
*/

{
  int i,j;
  printf("\n\n\n");
  for(i=0;i<row;i++)
   {
     for(j=0;j<col;j++)
	printf("\t %d",p[i][j]);
     printf("\n");
   }
}

Is it right way??

Always test it with YOUR compiler and system. If it's always accurate - and you get no warnings (of note), or crashes, or errors in the output - then you can say "I didn't find any bugs, at all!" ;)

Because you can never prove that a program of any complexity, has no bugs. You can only prove that it had no bugs that were found, in your tests.

vinitmittal2008 commented: Detailed and Usefull Information +1
Adak 419 Nearly a Posting Virtuoso
if((strcmp(string1, string2))==0) 
  string1 is equal to string2

or

int num = strcmp(string1, string2);
if(num==0) 
  strings are equal
else if(num < 1)
  string2 is greater than string1 //note the direction of 
   //the < (big "mouth", facing string2)
else
  string1 is greater than string 2 //string1 now has the "big mouth" of the > symbol
Caeon commented: Detailed and helpful +1
Adak 419 Nearly a Posting Virtuoso

Yes, malloc() returns NULL if the allocation failed. Did you include stdlib.h? Your cast of the pointer from malloc, is unnecessary in C, and will prevent the compiler from issuing an error regarding this oversight with stdlib.h.

I don't believe 1000 char's is too much, but check the other variable values to ensure that the buffer is not being freed, etc.

You want to check the pointer address at 307, not at 306, in your debugger. It will still be NULL until AFTER malloc returns the proper address, at the end of line 306, not at the start.

Adak 419 Nearly a Posting Virtuoso

Strings are not compared with the == sign in C. Use strcmp(). When it returns 0, then the strings are equal.

Adak 419 Nearly a Posting Virtuoso

Well, there is an easier and more efficient way to generate non-repeating random numbers. The algorithm is:

generate all the (non random) sequential numbers you need, and put them into an array (any data structure would perhaps do, but an array is easy).

Then shuffle the numbers in the array, randomly. Aha!

Then take the randomized numbers, in order, by their index: num[index].

Since all the numbers were unique to start with, and you've shuffled them around the array, in a random fashion, you're guaranteed a unique (pseudo) random number.

Most random numbers generated by non-professionals, are skewed in some way (which may not matter a bit to you and your program - you may not even notice it). There is a real art to generating good (pseudo) random numbers, however - not for beginners.

Adak 419 Nearly a Posting Virtuoso

Many apologies, but that last program was NOT the right version:

Try this one: (and delete that other one):

/* dynamically creates a 2D array of pointers, in C */

#include <stdio.h>
#include <stdlib.h>

double** allocate2D(int nrows, int ncols);

int main() {
  int i,j, rows, cols; 
  double **dat;

  printf("\n\n\n How many rows do you want?\n ");
  scanf("%d", &rows);
  (void) getchar();
  printf(" How many columns do you want?\n ");
  scanf("%d", &cols);
  (void) getchar();

  dat = allocate2D(rows, cols);
  for(i=0;i<rows;i++) {
    for(j=0;j<cols;j++) {
      dat[i][j] = i+j;
    }
  }

  for(i=0;i<rows;i++) {
      for(j=0;j<cols;j++) 
        printf("\n%.3lf", dat[i][j]);
  }
   
  for(i=0;i<rows;i++)
    free(dat[i]);

  free(dat);
  printf("\n\t\t\t    press enter when ready");
  (void) getchar();
  return 0;
}
double** allocate2D(int nrows, int ncols) {
     int i;
     double **dat2;
     /*  allocate array of pointers  */
     dat2 = malloc( nrows*sizeof(double*));
     
     /*  allocate each row  */
     
     for(i = 0; i < nrows; i++) {
          dat2[i] = malloc( ncols*sizeof(double));
     }
    if(dat2==NULL || dat2[i-1]==NULL) {
       printf("\nError allocating memory\n");
       exit(1);
    }
  return dat2;
}

The problem with my earlier post, is that it didn't return the address that malloc was assigning, to dat. :(

Since I can't edit that bad post, that will just be a lesson to anyone in a hurry, who doesn't read through the posts. ;)

Adak 419 Nearly a Posting Virtuoso

Welcome to the forum, Subclass! ;)

/* dynamically creats a 2D array of pointers, in C */

#include <stdio.h>
#include <stdlib.h>

void allocate2D(double **dat, int nrows, int ncols);

int main() {
  int i,j, rows, cols; 
  double **dat;
  
  printf("\n\n\nEnter the number of rows and columns you want: \n");
  scanf("%d %d", &rows, &cols);
  getchar();  //remove the newline from the kboard buffer
  
  
  allocate2D(dat, rows, cols);
  
  for(i=0;i<rows;i++) {
    for(j=0;j<cols;j++) {
      dat[i][j]= i+j;
    }
  }

  for(i=0;i<rows;i++) {
    printf("\n%.3lf %.3lf %.3lf", dat[i][0],dat[i][1],dat[i][2]);
  }

  //free the memory correctly
  for(i=0;i<rows;i++)
    free(dat[i]);
  free(dat);

  return 0;
}
void allocate2D(double **dat, int nrows, int ncols) {
     int i;
     /*  allocate array of pointers  */
     dat = malloc( nrows*sizeof( double* ) );
     
     /*  allocate each row  */
     
     for(i = 0; i < nrows; i++) {
          dat[i] = malloc( ncols*sizeof( double ) );
     }
    if(dat==NULL || dat[i-1]==NULL) {
       printf("\nError allocating memory\n");
       exit(1);
    }
   
}