Tutorials/C Programming Tutorial/Alliknow.c

From ThorstensHome
Revision as of 10:09, 18 October 2008 by WikiSysop (Talk)

Jump to: navigation, search
/* alliknow.c. Compile this with
g++ -I$QTDIR/include -L$QTDIR/lib -lqt-mt -o alliknow alliknow.cpp



Thorstens little explanations


First, read thinking in C++ by Bruce Eckels. It really helps a lot.

POINTERS *****************************************************************

int *i is a pointer to an int. 
cout << i << endl;
shows the address in mem.
cout << *i << endl;
shows the value.

i++ increases the pointer, so goes to the next int in mem.
*i++ is the same a *(i++), so it also increases the pointer.
(*i)++ increases the value in the mem by 1.

char *ch is a pointer to a char. It can consist of several characters, 
from the first character at the pointer till the first zero character.

char *ch; is the same as char* ch, but the * belongs to the variable name
to indicate it is a pointer. So, better write char *ch.

You can not do the following code:
char *ch;
*ch="hallo";

because at the second line, the pointer does not exist, as C does not know
where the free memory is. You must discover and allocate the free memory 
with malloc first:

char *ch;
ch=(char*)malloc(255);

for your convenience, you can also do an implicit malloc if the string 
length is known when creating the variable:

char *ch="hallo";

Variables that are known at compile time are laid onto the stack. Think of
a counter as an example. Variables that are set up during run time 
(think of books in bookstores: you do not know how many you need before
runtime) lodge in the heap. You cannot increase the size of variables on
the stack during runtime, but you can for variables in the heap. 
You get e.g. a variable on the stack with the command 
int i;
a variable in the stack, you get with malloc or new.
Remember to free the memory in the heap again, else, we speak of a memory 
leak.

Know that a pointer is always as big as you need to identify one atomic 
part (byte) in the memory. So, under ia32, a pointer is 32bit big, under
ia64, it is 64 bit big. And under C, an int is always as big as a pointer
under every architecture. So, you can calculate with pointers as with ints.
So, under ia32-C, an int is 32 bit big, under ia64, an int is 64 bit big.

global vs. local variables *****************************************************

a local variable is a variable that only exists for the duration of the function call.
See example below

*/

#include <stdio.h>
#include <stdlib.h>
#include <pwd.h>
#include <qapplication.h>
#include <qdialog.h>
#include <qlabel.h>
#include <qlayout.h>
#include <sys/types.h>
#include <iostream>
#include <dlfcn.h> // use of dynamic libraries

#include <qstring.h>

using namespace std; // otherwise, cin does not exist

int thorsten()
{
  int localvar=5; // this is a local variable.
}

int staticexample()
{
  static int often=0;
  often++;
  int comp=0;
  comp++;
  printf("You have called this function %d times\n",often);
  printf("this is always the same number: %d", comp);
}

int posix()
{
  printf("Now I want to show some posix programming\n");
  printf("First: getpwnam (man getpwnam)\n");
  struct passwd *rootpath;
  rootpath=getpwnam("root");
  printf("Home Directory of root is: ");
  printf(rootpath->pw_dir);
  printf("\n");
}

int input()
{
  printf(" * * * U S E R   I N P U T * * *\n");
  printf("please type something>");
  char ch2;
  (int)ch2=0;
  /* so lange ch, als Integer interpretiert, nicht den Wert 10 annimmt,
  /* wird das n�hste Zeichen gelesen */
  while((int)ch2!=10)
  {
    /* stdin ist die Standardeingabe, meist die Tastatur */
    ch2 = getc(stdin);
    /* putc erwartet einen Ganzzahl-Wert, um das entsprechende ASCII-Zeichen 
    /* auszugeben */
    /* stdout ist die Standardausgabe, meist der Bildschirm */
    putc((int)ch2,stdout);
  }
  printf("\nNow please type an int>");
  int i2=(int) getc(stdin);
  i2-=32;
  char cha[i2];
  for (int i3=0;i3<=i2;++i3)
  {
    cha[i3]='d';
    printf("%d\n",cha[i3]);
  }
}
  
int qt(int argc)
{
  // how to get a QString
  QString q=QString::fromLatin1("hello world",11);
  printf(q);
  printf("\n");
  char *argv[0];
  // how to get a QDialog
  // first, get a QApplication

  QApplication *qa=new QApplication(argc,argv);
  QDialog *dia1=new QDialog(0);

  QVBoxLayout *lay1 = new QVBoxLayout(dia1);
  
  QHBoxLayout *lay2 = new QHBoxLayout();
  lay1->addLayout(lay2);
  
  // The name of the widget
  QLabel *label = new QLabel( ("Please chose import/export function:"), dia1,"name" );
  
  lay1->addWidget( label );


  dia1->exec();
}

int dynlibuseexample() 
// this function demonstates the use of dynamic libraries
// from http://www.dwheeler.com/program-library/Program-Library-HOWTO/dl-libraries.html from the manpage of dlopen
{
  void *handle;
  double (*cosine)(double);
  char *error;
  double *test;

  handle = dlopen ("/lib/libm.so.6", RTLD_LAZY);
  if (!handle) {
    fputs (dlerror(), stderr);
    exit(1);
  }

  cosine = (double (*) (double)) (dlsym(handle, "cos"));
  if ((error = dlerror()) != NULL)  {
    fputs(error, stderr);
    exit(1);
  }

  printf ("%f\n", (*cosine)(2.0));
  dlclose(handle);
}

int main(int argc, char *argv[])
{
  thorsten();
  printf("This is a demo of Thorsten St�k\n");
  printf("alliknow.c, for Linux\n");
  printf("now I will try a system call (a shell command), ls\n");
  system("ls");
  printf("Why did you export your path as ");
  printf(getenv("PATH"));
  putenv("ALLIKNOW=done");
  printf("I now exported $ALLIKNOW as 'done'");
  printf(getenv("ALLIKNOW"));
  printf("Sorry, the var ALLIKNOW will not be 'done' to you.\n");
  printf("Now I demonstrate the use of pointers by printing hallo: ");
  char *ch;
  ch=(char*)malloc(255);
  ch="hallo";
  printf(ch);
  printf("\n");
  printf("Now I establish an array");
  int test[]={1};
  printf(", extend it");
  test[1]=2; 
  test[2]=NULL;
  printf(" and print it: ");
  int n=0;
  while (test[n]) 
  {
    printf("%d",test[n]);
    n++;
  }
  printf("Now I convert a number to a char\n");
  printf("first not-working");
  printf(l64a(65));
  printf("now working\n");
  char c[20];
  int i=65;
  printf("first, I want to show you how to print out an int\n");
  printf("%d",i);
  sprintf(c,"%d",i);
  printf(c);
  printf("What meanings can & have in a C-Program ?\n");
  printf("bitwise and, example: %d", 65&66);
  printf("find out memory-address of a var, example: %d", &c);
  printf("making a reference to a var, example :");
  int original=5;
  int &r=original;
  original=6;
  printf("%d",r);
  char choice;
  do 
  {
    printf("\nNow please chose what you want to see\n");
    printf(" i - C-style user-input\n");
    printf(" p - posix programming \n");
    printf(" t - qt programming \n");
    printf(" s - static example\n");
    printf(" d - dynamic library use\n");
    printf(" q - quit\n");
    cin >> choice;
    switch(choice) {
      case 'p' : posix(); break;
      case 'i' : input(); break;
      case 't' : qt(argc); break;
      case 's' : staticexample(); break;
      case 'd' : dynlibuseexample(); break;
      default: {};
    }   
  }
  while (choice != 'q');
  


}

#ifdef borland
/* PROGRAM AllIKnow;                                                        */

/* { Program BORLAND TURBO C++ 2.01D        }*/
/* Steht hinter & eine Char-Variable, wird sie far, siehe auch printf
/* Einer Char einen konkreten Buchstaben zuweisen:man setzt einen * davor   */
// & = AND; || = OR; == = =; != = NOT;
// Eine Bemerkung, die sich ber genau eine Zeile erstreckt
#include <stdio.h>/*<>bedeuten,dass er nur das IncludeVerzeichnis durchsucht*/
#if 1  /* Beispiel fr den Gebrauch von Compiler directives                 */
#endif
#include <conio.h>
#include "dos.h"
#include "iostream.h"
#include "graphics.h"
#include "process.h"

#include "ctype.h"
#include <string.h>


int i,k,j; /* globale Variablen                                             */
char near* near* a; // fr Execv

class Apfel{char near* Farbe;char near* Sorte;}; /* Class=RECORD            */

struct Mensch{char name[80];int telefon();}; /* Struct=OBJECT               */

int Mensch::telefon(){return 0;}

void Cursor_an()
  {asm MOV ah,01;
         asm MOV cx,$0607;
   asm INT $10;}

void Cursor_aus()
  {asm xor ax,ax;
   asm mov ah,01;
   asm mov cx,$2020;
   asm int $10;}

void torsten(void) /* function */
        {printf("Hallo");}

torsten(int a)
        {cout<< a;
        return 0;}

jochen(void)
        {return 0;}

abstrakt(int r)
        {r=5;
        return r;}

/* #include "main.h" /*(c)Jochen Strk.Hier werden alle Prozeduren eingefgt   */

main(int argc, char *argv[])
        {char Thorsten;
        char buchstabe;
        char near *Buchstabenkette;/* Man kann mehrere Buchstaben direkt zuweisen.*/
        Buchstabenkette="Hallo";
        Buchstabenkette="Hallo"", du";/*Addieren von Texten                         */
        clrscr();
        while(argc=0)
        {break;}
        textmode(C4350); // c4350 = 64
        struct Mensch gt; /* Eigene Typendefinition                               */
        gt.telefon();
        int c; /* var */
        float Gleitkomma;
        double Doppelt;
        long lang;
        char Name[80]; /* Die Stringvariable Name ist 80 Zeichen lang             */
        system("dir"); /* funktioniert nur in der compilierten Fassung            */
        cprintf("Ich sage ");
        printf("Hallo");
        cout<<" Welt ";
        torsten();  /* das */
        torsten(1); /* und das sind zwei verschiedene Funktionen */
        jochen; /* Erzeugt ein Warning */
        Thorsten=*"a";/*Einen konkreten Buchstaben einer Char-Variable zuweisen   */
        Thorsten=Thorsten,Thorsten;/* Addieren von Strings                        */
        printf("\nstrcat \n");
        printf(&Thorsten);
        printf(strcat(&Thorsten,"Hallo"));
        Thorsten=toupper(Thorsten);/* a ---> A                                    */
        Cursor_aus();
        i=1;
        printf("%i",i); /*{ Umwandlung von INT in CHAR}                           */
        buchstabe=*"a"; /*{ Umwandlung von Char in Char near*}                    */
        // Char hat ein Byte, char near* ist eine Zeichenkette
        buchstabe=*"Torsten";//bei der Umwandlung wird natrlich nur1Byte genommen
        printf(&buchstabe);
        printf("Parameter : \n");
        printf(argv[1]);
        printf("\n Variablenbelegung \n");
        Thorsten=(char)"Hallo";
        printf(&Thorsten);
        printf("\n Abstrakte Variablenbetrachtung: \n");
        c=1;
        abstrakt(c);
        if (c=5) printf("5");
        printf("\n Umwandlung von Int in Char: Ord, Asc, Val, Str\n");
        int h;
        h=*"F"; // h = 70
        printf("\n Umwandlung von Char in Int: Str, Ord, Asc, Val\n");
        char th;
        th=70; // th = 70
        Thorsten=getch();
        Cursor_an();
        /* init16(); */
        outtextxy(1,1,&Thorsten); /*Steht hinter & eine Char-Variable,wird sie far*/
        outtextxy(1,1,"Thorsten"); // Nichts ist dasselbe wie &*
        outtextxy(1,1,&*"Thorsten"); // Ein & nimmt ein * wieder weg
        outtextxy(1,1,&*"Thorsten"); /* Vor return 0; kann man kein ; weglassen   */
        if (0<1<2);
        poke(0x0000,0x0417,32);/*Numlock an                                       */
        delay(1000);
        closegraph();
        ende:
        exit(0); /* beendet das laufende Programm                                 */
        return 0;} /* Hinter return 0 kann man kein ; weglassen                   */
#endif