Search Results

Search found 1848 results on 74 pages for 'printf'.

Page 15/74 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Template function overloading with identical signatures, why does this work?

    - by user1843978
    Minimal program: #include <stdio.h> #include <type_traits> template<typename S, typename T> int foo(typename T::type s) { return 1; } template<typename S, typename T> int foo(S s) { return 2; } int main(int argc, char* argv[]) { int x = 3; printf("%d\n", foo<int, std::enable_if<true, int>>(x)); return 0; } output: 1 Why doesn't this give a compile error? When the template code is generated, wouldn't the functions int foo(typename T::type search) and int foo(S& search) have the same signature? If you change the template function signatures a little bit, it still works (as I would expect given the example above): template<typename S, typename T> void foo(typename T::type s) { printf("a\n"); } template<typename S, typename T> void foo(S s) { printf("b\n"); } Yet this doesn't and yet the only difference is that one has an int signature and the other is defined by the first template parameter. template<typename T> void foo(typename T::type s) { printf("a\n"); } template<typename T> void foo(int s) { printf("b\n"); } I'm using code similar to this for a project I'm working on and I'm afraid that there's a subtly to the language that I'm not understanding that will cause some undefined behavior in certain cases. I should also mention that it does compile on both Clang and in VS11 so I don't think it's just a compiler bug.

    Read the article

  • Searching strings C

    - by Skittles
    First time posting here so I'm sorry if I mess up. I need to search a string and return any strings containing the search data with the search data highlighted. If my string is Hi my name is and I searched name it would produce Hi my NAME is This is a quick code I wrote that works but it only works once. If I try and search again it seg faults. I was hoping someone could hint me at a better way to write this because this code is disgusting! void search(char * srcStr, int n){ int cnt = 0, pnt,i = 0; char tmpText[500]; char tmpName[500]; char *ptr, *ptr2, *ptrLast; int num; while(*(node->text+cnt) != '\0'){ //finds length of string cnt++; } for(pnt = 0; pnt < cnt; pnt++){ //copies node->text into a tmp string tmpText[pnt] = *(node->text+pnt); } tmpText[pnt+1] = '\0'; //prints up to first occurrence of srcStr ptr = strcasestr(tmpText, srcStr); for(num = 0; num < ptr-tmpText; num++){ printf("%c",tmpText[num]); } //prints first occurrence of srcStr in capitals for(num = 0; num < n; num++){ printf("%c",toupper(tmpText[ptr-tmpText+num])); } ptr2 = strcasestr((ptr+n),srcStr); for(num = (ptr-tmpText+n); num < (ptr2-tmpText); num++){ printf("%c",tmpText[num]); } while((ptr = strcasestr((ptr+n), srcStr)) != NULL){ ptr2 = strcasestr((ptr+n),srcStr); for(num = (ptr-tmpText+n); num < (ptr2-tmpText); num++){ printf("%c",tmpText[num]); } for(num = 0; num < n; num++){ printf("%c",toupper(tmpText[ptr-tmpText+num])); } ptrLast = ptr; } //prints remaining string after last occurrence for(num = (ptrLast-tmpText+n); num < cnt; num++){ printf("%c",tmpText[num]); } }

    Read the article

  • having an issue about the output in c programming ..

    - by user2985811
    i'm having a problem on running the output after putting the input.. the output doesn't show after i put the variables and i don't know how to set the code .. so if you guys could help me with this, that would be grateful.. #include <stdio.h> #include <conio.h> int read_temps (float temps[]); int hot_days (int numOfTemp, float temps[]); int printf_temps (int numOfTemp, float temps[], int numOfHotDays); int main (void) { int index = 0; float tempVal; float temps[31]; int numOfTemp, numOfHotDays; do { printf ("Enter the temperature:"); scanf ("%f", &tempVal); if (tempVal!=-500.0) { temps[index] = tempVal; index++; } } while (tempVal != -500.0); return ; { int i; int count = 0; for (i = 0; i < numOfTemp; i++) { if (temps[i] > 32.0) count++; } return count; } { float sum = 0.0; int i; printf ("\nInput Temperatures:"); printf ("\n-------------------------"); for (i = 0;i < numOfTemp; i++) { printf ("\nDay %d : %.2fF", i+1, temps[i]); sum = sum + temps[i]; } printf ("\nNumber of Hot Days : %d", numOfHotDays); printf ("\nAverage Temperature: %.2f", sum/numOfTemp); } { clrscr (); numOfTemp = read_temps (temps); numOfHotDays = hot_days (numOfTemp, temps); clrscr (); printf_temps (numOfTemp, temps, numOfHotDays); getch (); } }

    Read the article

  • Informaton of pendriver with libudv on linux

    - by Catanzaro
    I'm doing a little app in C that read the driver information of my pendrive: Plugged it and typed dmesg: [ 7676.243994] scsi 7:0:0:0: Direct-Access Lexar USB Flash Drive 1100 PQ: 0 ANSI: 0 CCS [ 7676.248359] sd 7:0:0:0: Attached scsi generic sg2 type 0 [ 7676.256733] sd 7:0:0:0: [sdb] 7831552 512-byte logical blocks: (4.00 GB/3.73 GiB) [ 7676.266559] sd 7:0:0:0: [sdb] Write Protect is off [ 7676.266566] sd 7:0:0:0: [sdb] Mode Sense: 43 00 00 00 [ 7676.266569] sd 7:0:0:0: [sdb] Assuming drive cache: write through [ 7676.285373] sd 7:0:0:0: [sdb] Assuming drive cache: write through [ 7676.285383] sdb: sdb1 [ 7676.298661] sd 7:0:0:0: [sdb] Assuming drive cache: write through [ 7676.298667] sd 7:0:0:0: [sdb] Attached SCSI removable disk with "udevadm info -q all -n /dev/sdb" P: /devices/pci0000:00/0000:00:11.0/0000:02:03.0/usb1/1-1/1-1:1.0/host7/target7:0:0/7:0:0:0/block/sdb N: sdb W: 36 S: block/8:16 S: disk/by-id/usb-Lexar_USB_Flash_Drive_AA5OCYQII8PSQXBB-0:0 S: disk/by-path/pci-0000:02:03.0-usb-0:1:1.0-scsi-0:0:0:0 E: UDEV_LOG=3 E: DEVPATH=/devices/pci0000:00/0000:00:11.0/0000:02:03.0/usb1/1-1/1-1:1.0/host7/target7:0:0/7:0:0:0/block/sdb E: MAJOR=8 E: MINOR=16 E: DEVNAME=/dev/sdb E: DEVTYPE=disk E: SUBSYSTEM=block E: ID_VENDOR=Lexar E: ID_VENDOR_ENC=Lexar\x20\x20\x20 E: ID_VENDOR_ID=05dc E: ID_MODEL=USB_Flash_Drive E: ID_MODEL_ENC=USB\x20Flash\x20Drive\x20 E: ID_MODEL_ID=a813 E: ID_REVISION=1100 E: ID_SERIAL=Lexar_USB_Flash_Drive_AA5OCYQII8PSQXBB-0:0 E: ID_SERIAL_SHORT=AA5OCYQII8PSQXBB E: ID_TYPE=disk E: ID_INSTANCE=0:0 E: ID_BUS=usb E: ID_USB_INTERFACES=:080650: E: ID_USB_INTERFACE_NUM=00 E: ID_USB_DRIVER=usb-storage E: ID_PATH=pci-0000:02:03.0-usb-0:1:1.0-scsi-0:0:0:0 E: ID_PART_TABLE_TYPE=dos E: UDISKS_PRESENTATION_NOPOLICY=0 E: UDISKS_PARTITION_TABLE=1 E: UDISKS_PARTITION_TABLE_SCHEME=mbr E: UDISKS_PARTITION_TABLE_COUNT=1 E: DEVLINKS=/dev/block/8:16 /dev/disk/by-id/usb-Lexar_USB_Flash_Drive_AA5OCYQII8PSQXBB-0:0 /dev/disk/by-path/pci-0000:02:03.0-usb-0:1:1.0-scsi-0:0:0:0 and my software is: Codice: Seleziona tutto #include <stdio.h> #include <libudev.h> #include <stdlib.h> #include <locale.h> #include <unistd.h> int main(void) { struct udev_enumerate *enumerate; struct udev_list_entry *devices, *dev_list_entry; struct udev_device *dev; /* Create the udev object */ struct udev *udev = udev_new(); if (!udev) { printf("Can't create udev\n"); exit(0); } enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_subsystem(enumerate, "scsi_generic"); udev_enumerate_scan_devices(enumerate); devices = udev_enumerate_get_list_entry(enumerate); udev_list_entry_foreach(dev_list_entry, devices) { const char *path; /* Get the filename of the /sys entry for the device and create a udev_device object (dev) representing it */ path = udev_list_entry_get_name(dev_list_entry); dev = udev_device_new_from_syspath(udev, path); /* usb_device_get_devnode() returns the path to the device node itself in /dev. */ printf("Device Node Path: %s\n", udev_device_get_devnode(dev)); /* The device pointed to by dev contains information about the hidraw device. In order to get information about the USB device, get the parent device with the subsystem/devtype pair of "usb"/"usb_device". This will be several levels up the tree, but the function will find it.*/ dev = udev_device_get_parent_with_subsystem_devtype( dev, "block", "disk"); if (!dev) { printf("Errore\n"); exit(1); } /* From here, we can call get_sysattr_value() for each file in the device's /sys entry. The strings passed into these functions (idProduct, idVendor, serial, etc.) correspond directly to the files in the directory which represents the USB device. Note that USB strings are Unicode, UCS2 encoded, but the strings returned from udev_device_get_sysattr_value() are UTF-8 encoded. */ printf(" VID/PID: %s %s\n", udev_device_get_sysattr_value(dev,"idVendor"), udev_device_get_sysattr_value(dev, "idProduct")); printf(" %s\n %s\n", udev_device_get_sysattr_value(dev,"manufacturer"), udev_device_get_sysattr_value(dev,"product")); printf(" serial: %s\n", udev_device_get_sysattr_value(dev, "serial")); udev_device_unref(dev); } /* Free the enumerator object */ udev_enumerate_unref(enumerate); udev_unref(udev); return 0; } the problem is that i obtain in output: Device Node Path: /dev/sg0 Errore and dont view information. subsystem and the devtype i think that are inserted well : "block" and "disk". thanks for help. Bye

    Read the article

  • Calculix Data Visualiser using QT

    - by Ann
    I am doing a project on CalculiX data visualizor,using Qt.I 've to draw the structure and after giving force the displacement should be shawn as variation in color.I chose HSV coloring,but while executing I got an error message:"QColor::from Hsv:HSV parameters out of range".The code is: DataViz1::DataViz1(QWidget *parent) : QWidget(parent), ui(new Ui::DataViz1) { DArea = new QGLScreen(this); DArea-setGeometry(QRect(10,10,700,600)); //TODO This values are feeded by user dfile="/home/41407/color.txt";//input file with displacement mfile="/home/41407/mesh21.txt";//input file nodeId="*NODE"; elId="*ELEMENT"; DataId="displ"; parseMfile(); parseDfile(); DArea->Nodes=Nodes; DArea->Elements=Elements; DArea->Data=Data; DArea->fillColorArray(); //printf("Colr is %d",DArea->pickColor(-11.02,0));fflush(stdout); ui->setupUi(this); } DataViz1::~DataViz1() { delete ui; } void DataViz1::parseMfile() { QFile file(mfile); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; int node_end=0; QTextStream in(&file); in.skipWhiteSpace(); while (!in.atEnd()) { QString line = in.readLine(); if(line.startsWith(nodeId))//Node block in Mfile { while(1) { line = in.readLine(); if(line.startsWith(elId)) { break; } Nodes< while(1) { line = in.readLine(); Elements<<line; //printf("Element is %s\n",line.toLocal8Bit().constData());fflush(stdout); if(in.atEnd()) break; } } } } void DataViz1::parseDfile() { QFile file(dfile); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; int node_end=0; QTextStream in(&file); in.skipWhiteSpace(); while (!in.atEnd()) { QString line = in.readLine(); if(line.startsWith(DataId)) { continue; } line = in.readLine(); Data< } /......................................................................../ include "qglscreen.h" include GLfloat LightAmbient[]= { 0.5f, 0.5f, 0.5f, 1.0f }; GLfloat LightDiffuse[]= { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat LightPosition[]= { 0.0f, 0.0f, 2.0f, 1.0f }; QGLScreen::QGLScreen(QWidget *parent):QGLWidget(QGLFormat(QGL::SampleBuffers), parent) { clearColor = Qt::black; xRot = 0; yRot = 0; zRot = 0; ifdef QT_OPENGL_ES_2 program = 0; endif //TODO user input ElType="HE8"; DType="SolidFrame"; axis="X"; } QGLScreen::~QGLScreen() { } QSize QGLScreen::minimumSizeHint() const { return QSize(50, 50); } QSize QGLScreen::sizeHint() const { return QSize(200, 200); } void QGLScreen::setClearColor(const QColor &color) { clearColor = color; updateGL(); } void QGLScreen::initializeGL() { xRot=0; yRot=0; zRot=0; scaling = 1.0; /* select clearing (background) color */ glClearColor (0.0, 0.0, 0.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // glViewport(0,0,10,10); glOrtho(-10.0, +10.0, -10.0, +10.0, -10.0,+10.0); glEnable (GL_LINE_SMOOTH); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); } void QGLScreen::wheel1() { scaling1 += .0025; count2++; update(); } void QGLScreen::wheel2() { if(count2-14) { scaling1 -= .0025; count2--; update(); } } void QGLScreen::drawModel(int x1,int y1,int x2,int y2) { makeCurrent(); QStringList Cnode,Celement; for (int i = 0; i < Elements.size(); ++i) { Celement=Elements.at(i).split(","); // printf("Element is %s",Celement.at(0).toLocal8Bit().constData());fflush(stdout); //printf("Node at el is %s\n",(findNode(Celement.at(1).toInt())).at(1).toLocal8Bit().constData()); fflush(stdout); if(ElType=="HE8") { //First four nodes float ENX1=(findNode(Celement.at(1).toInt())).at(1).toDouble(); float ENX2=(findNode(Celement.at(2).toInt())).at(1).toDouble(); float ENX3=(findNode(Celement.at(3).toInt())).at(1).toDouble(); float ENX4=(findNode(Celement.at(4).toInt())).at(1).toDouble(); float ENY1=(findNode(Celement.at(1).toInt())).at(2).toDouble(); float ENY2=(findNode(Celement.at(2).toInt())).at(2).toDouble(); float ENY3=(findNode(Celement.at(3).toInt())).at(2).toDouble(); float ENY4=(findNode(Celement.at(4).toInt())).at(2).toDouble(); float ENZ1=(findNode(Celement.at(1).toInt())).at(3).toDouble(); float ENZ2=(findNode(Celement.at(2).toInt())).at(3).toDouble(); float ENZ3=(findNode(Celement.at(3).toInt())).at(3).toDouble(); float ENZ4=(findNode(Celement.at(4).toInt())).at(3).toDouble(); //Second four Nodes float ENX5=(findNode(Celement.at(5).toInt())).at(1).toDouble(); float ENX6=(findNode(Celement.at(6).toInt())).at(1).toDouble(); float ENX7=(findNode(Celement.at(7).toInt())).at(1).toDouble(); float ENX8=(findNode(Celement.at(8).toInt())).at(1).toDouble(); float ENY5=(findNode(Celement.at(5).toInt())).at(2).toDouble(); float ENY6=(findNode(Celement.at(6).toInt())).at(2).toDouble(); float ENY7=(findNode(Celement.at(7).toInt())).at(2).toDouble(); float ENY8=(findNode(Celement.at(8).toInt())).at(2).toDouble(); float ENZ5=(findNode(Celement.at(5).toInt())).at(3).toDouble(); float ENZ6=(findNode(Celement.at(6).toInt())).at(3).toDouble(); float ENZ7=(findNode(Celement.at(7).toInt())).at(3).toDouble(); float ENZ8=(findNode(Celement.at(8).toInt())).at(3).toDouble(); //Identify Colors GLfloat ENC[8][3]; for(int k=1;k<8;k++) { int hsv=pickColor(findData(Celement.at(k).toInt()).toDouble(),0); //printf("hsv is %d=",hsv);fflush(stdout); getRGB(hsv); //printf("%d*%d*%d\n",red,green,blue); //ENC[k]={red,green,blue}; ENC[k][0]=red; ENC[k][1]=green; ENC[k][2]=blue; } //Plot the first four direct loop if(DType=="WireFrame"){ glBegin(GL_LINE_LOOP); glColor3f(255,0,0); glVertex3f(ENX1,ENY1,ENZ1); glColor3f(255,0,0); glVertex3f(ENX2,ENY2,ENZ2); glColor3f(255,0,0); glVertex3f(ENX3,ENY3,ENZ3); glColor3f(255,0,0); glVertex3f(ENX4,ENY4,ENZ4); glEnd(); //Plot the second four direct loop glBegin(GL_LINE_LOOP); glColor3f(0,0,255); glVertex3f(ENX5,ENY5,ENZ5); glColor3f(0,0,255); glVertex3f(ENX6,ENY6,ENZ6); glColor3f(0,0,255); glVertex3f(ENX7,ENY7,ENZ7); glColor3f(0,0,255); glVertex3f(ENX8,ENY8,ENZ8); glEnd(); //Plot the interconnections glBegin(GL_LINE); glColor3f(150,150,150); glVertex3f(ENX1,ENY1,ENZ1); glVertex3f(ENX5,ENY5,ENZ5); glEnd(); glBegin(GL_LINE); glColor3f(150,150,150); glVertex3f(ENX2,ENY2,ENZ2); glVertex3f(ENX6,ENY6,ENZ6); glEnd(); glBegin(GL_LINE); glColor3f(150,150,150); glVertex3f(ENX3,ENY3,ENZ3); glVertex3f(ENX7,ENY7,ENZ7); glEnd(); glBegin(GL_LINE); glColor3f(150,150,150); glVertex3f(ENX4,ENY4,ENZ4); glVertex3f(ENX8,ENY8,ENZ8); glEnd(); } if(DType=="SolidFrame") { glBegin(GL_QUADS); glColor3fv(ENC[1]); glVertex3f(ENX1,ENY1,ENZ1); glColor3fv(ENC[2]); glVertex3f(ENX2,ENY2,ENZ2); glColor3fv(ENC[3]); glVertex3f(ENX3,ENY3,ENZ3); glColor3fv(ENC[4]); glVertex3f(ENX4,ENY4,ENZ4); glEnd(); //break; glBegin(GL_QUADS); glColor3fv(ENC[5]); glVertex3f(ENX5,ENY5,ENZ5); glColor3fv(ENC[6]); glVertex3f(ENX6,ENY6,ENZ6); glColor3fv(ENC[7]); glVertex3f(ENX7,ENY7,ENZ7); glColor3fv(ENC[8]); glVertex3f(ENX8,ENY8,ENZ8); glEnd(); glBegin(GL_QUAD_STRIP); glColor3fv(ENC[1]); glVertex3f(ENX1,ENY1,ENZ1); glColor3fv(ENC[5]); glVertex3f(ENX5,ENY5,ENZ5); glColor3fv(ENC[2]); glVertex3f(ENX2,ENY2,ENZ2); glColor3fv(ENC[6]); glVertex3f(ENX6,ENY6,ENZ6); glEnd(); glBegin(GL_QUAD_STRIP); glColor3fv(ENC[3]); glVertex3f(ENX3,ENY3,ENZ3); glColor3fv(ENC[7]); glVertex3f(ENX7,ENY7,ENZ7); glColor3fv(ENC[4]); glVertex3f(ENX4,ENY4,ENZ4); glColor3fv(ENC[8]); glVertex3f(ENX8,ENY8,ENZ8); glEnd(); glBegin(GL_QUAD_STRIP); glColor3fv(ENC[2]); glVertex3f(ENX2,ENY2,ENZ2); glColor3fv(ENC[6]); glVertex3f(ENX6,ENY6,ENZ6); glColor3fv(ENC[3]); glVertex3f(ENX3,ENY3,ENZ3); glColor3fv(ENC[7]); glVertex3f(ENX7,ENY7,ENZ7); glEnd(); glBegin(GL_QUAD_STRIP); glColor3fv(ENC[1]); glVertex3f(ENX1,ENY1,ENZ1); glColor3fv(ENC[5]); glVertex3f(ENX5,ENY5,ENZ5); glColor3fv(ENC[4]); glVertex3f(ENX4,ENY4,ENZ4); glColor3fv(ENC[8]); glVertex3f(ENX8,ENY8,ENZ8); glEnd(); } } } } QStringList QGLScreen::findNode(int element) { QStringList Temp; for (int i = 0; i < Nodes.size(); ++i) { Temp=Nodes.at(i).split(","); if(Temp.at(0).toInt()==element) { break; } } return Temp; } QString QGLScreen::findData(int Node) { QString Temp; QRegExp sep("\s+"); for (int i = 0; i < Data.size(); ++i) { if((Data.at(i).split("\t")).at(0).section(sep,1,1).toInt()==Node) { if(axis=="X") { Temp=Data.at(i).split("\t").at(0).section(sep,2,2); } if(axis=="Y") { Temp=Data.at(i).split("\t").at(0).section(sep,3,3); } if(axis=="Z") { Temp=Data.at(i).split("\t").at(0).section(sep,4,4); } break; } } return Temp; } void QGLScreen::fillColorArray() { QString Temp1,Temp2,Temp3; double d1s=0,d2s=0,d3s=0,d1l=0,d2l=0,d3l=0,diff=0; QRegExp sep("\\s+"); for (int i = 0; i < Data.size(); ++i) { Temp1=(Data.at(i).split("\t")).at(0).section(sep,2,2); if(d1s>Temp1.toDouble()) { d1s=Temp1.toDouble(); } if(d1l<Temp1.toDouble()) { d1l=Temp1.toDouble(); } Temp2=(Data.at(i).split("\t")).at(0).section(sep,3,3); if(d2s>Temp2.toDouble()) { d2s=Temp2.toDouble(); } if(d2l<Temp2.toDouble()) { d2l=Temp2.toDouble(); } Temp3=(Data.at(i).split("\t")).at(0).section(sep,4,4); if(d3s>Temp3.toDouble()) { d3s=Temp3.toDouble(); } if(d3l<Temp3.toDouble()) { d3l=Temp3.toDouble(); } // printf("data is %s",Temp.toLocal8Bit().constData());fflush(stdout); } color[0][0]=d1l; for(int i=1;i<360;i++) { //printf("Large is%f small is %f",d1l,d1s); diff=d1l-d1s; if(d1l==0&&d1s<0) color[0][i]=color[0][i-1]-diff/360; else if(d1l>0&&d1s==0) color[0][i]=color[0][i-1]+diff/360; else if(d1l>0&&d1s<0) color[0][i]=color[0][i-1]-diff/360; diff=d2l-d2s; if(d2l==0&&d2s<0) color[1][i]=color[1][i-1]-diff/360; else if(d2l>0&&d2s==0) color[1][i]=color[1][i-1]+diff/360; else if(d2l>0&&d2s<0) color[1][i]=color[1][i-1]-diff/360; diff=d3l-d3s; if(d3l==0&&d3s<0) color[2][i]=color[2][i-1]-diff/360; else if(d3l>0&&d3s==0) color[2][i]=color[2][i-1]+diff/360; else if(d3l>0&&d3s<0) color[2][i]=color[2][i-1]-diff/360; } //for(int i=0;i<360;i++) printf("%d %f %f %f\n",i,color[0][i],color[1][i],color[2][i]); } int QGLScreen::pickColor(double data,int Did) { int i,pos; if(axis=="X")Did=0; if(axis=="Y")Did=1; if(axis=="Z")Did=2; //printf("%f data is",data);fflush(stdout); for(int i=0;i<360;i++) { if(color[Did][i]<data && data>color[Did][i+1]) { //printf("Orginal dat is %f Data found is %f and pos %d\n",data,color[Did][i],i);fflush(stdout); pos=i; break; } } return pos; } void QGLScreen::getRGB(int hsv) { QColor c; c.setHsv(hsv,255,255,255); QColor r=QColor::fromHsv(hsv,255,255); red=r.red(); green=r.green(); blue=r.blue(); } void QGLScreen::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushAttrib(GL_ALL_ATTRIB_BITS); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); GLfloat x = 3.0 * GLfloat(width()) / height(); glOrtho(-x, +x, -3.0, +3.0, 4.0, 15.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(0.0, 0.0, -10.0); glScalef(scaling, scaling, scaling); glRotatef(xRot, 1.0, 0.0, 0.0); glRotatef(yRot, 0.0, 1.0, 0.0); glRotatef(zRot, 0.0, 0.0, 1.0); drawModel(0,0,1,1); /* don't wait! * start processing buffered OpenGL routines */ glFlush (); } /void QGLScreen::zoom1() { scaling+=.05; update(); }/ void QGLScreen::resizeGL(int width, int height) { int side = qMin(width, height); glViewport((width - side) / 2, (height - side) / 2, side, side); #if !defined(QT_OPENGL_ES_2) glMatrixMode(GL_PROJECTION); glLoadIdentity(); #ifndef QT_OPENGL_ES glOrtho(-0.5, +0.5, +0.5, -0.5, 4.0, 15.0); #else glOrthof(-0.5, +0.5, +0.5, -0.5, 4.0, 15.0); #endif glMatrixMode(GL_MODELVIEW); #endif } void QGLScreen::mousePressEvent(QMouseEvent *event) { lastPos = event-pos(); } void QGLScreen::mouseMoveEvent(QMouseEvent *event) { GLfloat dx = GLfloat(event->x() - lastPos.x()) / width(); GLfloat dy = GLfloat(event->y() - lastPos.y()) / height(); if (event->buttons() & Qt::LeftButton) { xRot+= 180 * dy; yRot += 180 * dx; update(); } else if (event->buttons() & Qt::RightButton) { xRot += 180 * dy; yRot += 180 * dx; update(); } lastPos = event->pos(); } void QGLScreen::mouseReleaseEvent(QMouseEvent * /* event */) { emit clicked(); }

    Read the article

  • Convert Java program to C

    - by imicrothinking
    I need a bit of guidance with writing a C program...a bit of quick background as to my level, I've programmed in Java previously, but this is my first time programming in C, and we've been tasked to translate a word count program from Java to C that consists of the following: Read a file from memory Count the words in the file For each occurrence of a unique word, keep a word counter variable Print out the top ten most frequent words and their corresponding occurrences Here's the source program in Java: package lab0; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; public class WordCount { private ArrayList<WordCountNode> outputlist = null; public WordCount(){ this.outputlist = new ArrayList<WordCountNode>(); } /** * Read the file into memory. * * @param filename name of the file. * @return content of the file. * @throws Exception if the file is too large or other file related exception. */ public char[] readFile(String filename) throws Exception{ char [] result = null; File file = new File(filename); long size = file.length(); if (size > Integer.MAX_VALUE){ throw new Exception("File is too large"); } result = new char[(int)size]; FileReader reader = new FileReader(file); int len, offset = 0, size2read = (int)size; while(size2read > 0){ len = reader.read(result, offset, size2read); if(len == -1) break; size2read -= len; offset += len; } return result; } /** * Make article word by word. * * @param article the content of file to be counted. * @return string contains only letters and "'". */ private enum SPLIT_STATE {IN_WORD, NOT_IN_WORD}; /** * Go through article, find all the words and add to output list * with their count. * * @param article the content of the file to be counted. * @return words in the file and their counts. */ public ArrayList<WordCountNode> countWords(char[] article){ SPLIT_STATE state = SPLIT_STATE.NOT_IN_WORD; if(null == article) return null; char curr_ltr; int curr_start = 0; for(int i = 0; i < article.length; i++){ curr_ltr = Character.toUpperCase( article[i]); if(state == SPLIT_STATE.IN_WORD){ article[i] = curr_ltr; if ((curr_ltr < 'A' || curr_ltr > 'Z') && curr_ltr != '\'') { article[i] = ' '; //printf("\nthe word is %s\n\n",curr_start); if(i - curr_start < 0){ System.out.println("i = " + i + " curr_start = " + curr_start); } addWord(new String(article, curr_start, i-curr_start)); state = SPLIT_STATE.NOT_IN_WORD; } }else{ if (curr_ltr >= 'A' && curr_ltr <= 'Z') { curr_start = i; article[i] = curr_ltr; state = SPLIT_STATE.IN_WORD; } } } return outputlist; } /** * Add the word to output list. */ public void addWord(String word){ int pos = dobsearch(word); if(pos >= outputlist.size()){ outputlist.add(new WordCountNode(1L, word)); }else{ WordCountNode tmp = outputlist.get(pos); if(tmp.getWord().compareTo(word) == 0){ tmp.setCount(tmp.getCount() + 1); }else{ outputlist.add(pos, new WordCountNode(1L, word)); } } } /** * Search the output list and return the position to put word. * @param word is the word to be put into output list. * @return position in the output list to insert the word. */ public int dobsearch(String word){ int cmp, high = outputlist.size(), low = -1, next; // Binary search the array to find the key while (high - low > 1) { next = (high + low) / 2; // all in upper case cmp = word.compareTo((outputlist.get(next)).getWord()); if (cmp == 0) return next; else if (cmp < 0) high = next; else low = next; } return high; } public static void main(String args[]){ // handle input if (args.length == 0){ System.out.println("USAGE: WordCount <filename> [Top # of results to display]\n"); System.exit(1); } String filename = args[0]; int dispnum; try{ dispnum = Integer.parseInt(args[1]); }catch(Exception e){ dispnum = 10; } long start_time = Calendar.getInstance().getTimeInMillis(); WordCount wordcount = new WordCount(); System.out.println("Wordcount: Running..."); // read file char[] input = null; try { input = wordcount.readFile(filename); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } // count all word ArrayList<WordCountNode> result = wordcount.countWords(input); long end_time = Calendar.getInstance().getTimeInMillis(); System.out.println("wordcount: completed " + (end_time - start_time)/1000000 + "." + (end_time - start_time)%1000000 + "(s)"); System.out.println("wordsort: running ..."); start_time = Calendar.getInstance().getTimeInMillis(); Collections.sort(result); end_time = Calendar.getInstance().getTimeInMillis(); System.out.println("wordsort: completed " + (end_time - start_time)/1000000 + "." + (end_time - start_time)%1000000 + "(s)"); Collections.reverse(result); System.out.println("\nresults (TOP "+ dispnum +" from "+ result.size() +"):\n" ); // print out result String str ; for (int i = 0; i < result.size() && i < dispnum; i++){ if(result.get(i).getWord().length() > 15) str = result.get(i).getWord().substring(0, 14); else str = result.get(i).getWord(); System.out.println(str + " - " + result.get(i).getCount()); } } public class WordCountNode implements Comparable{ private String word; private long count; public WordCountNode(long count, String word){ this.count = count; this.word = word; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public int compareTo(Object arg0) { // TODO Auto-generated method stub WordCountNode obj = (WordCountNode)arg0; if( count - obj.getCount() < 0) return -1; else if( count - obj.getCount() == 0) return 0; else return 1; } } } Here's my attempt (so far) in C: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> // Read in a file FILE *readFile (char filename[]) { FILE *inputFile; inputFile = fopen (filename, "r"); if (inputFile == NULL) { printf ("File could not be opened.\n"); exit (EXIT_FAILURE); } return inputFile; } // Return number of words in an array int wordCount (FILE *filePointer, char filename[]) {//, char *words[]) { // count words int count = 0; char temp; while ((temp = getc(filePointer)) != EOF) { //printf ("%c", temp); if ((temp == ' ' || temp == '\n') && (temp != '\'')) count++; } count += 1; // counting method uses space AFTER last character in word - the last space // of the last character isn't counted - off by one error // close file fclose (filePointer); return count; } // Print out the frequencies of the 10 most frequent words in the console int main (int argc, char *argv[]) { /* Step 1: Read in file and check for errors */ FILE *filePointer; filePointer = readFile (argv[1]); /* Step 2: Do a word count to prep for array size */ int count = wordCount (filePointer, argv[1]); printf ("Number of words is: %i\n", count); /* Step 3: Create a 2D array to store words in the file */ // open file to reset marker to beginning of file filePointer = fopen (argv[1], "r"); // store words in character array (each element in array = consecutive word) char allWords[count][100]; // 100 is an arbitrary size - max length of word int i,j; char temp; for (i = 0; i < count; i++) { for (j = 0; j < 100; j++) { // labels are used with goto statements, not loops in C temp = getc(filePointer); if ((temp == ' ' || temp == '\n' || temp == EOF) && (temp != '\'') ) { allWords[i][j] = '\0'; break; } else { allWords[i][j] = temp; } printf ("%c", allWords[i][j]); } printf ("\n"); } // close file fclose (filePointer); /* Step 4: Use a simple selection sort algorithm to sort 2D char array */ // PStep 1: Compare two char arrays, and if // (a) c1 > c2, return 2 // (b) c1 == c2, return 1 // (c) c1 < c2, return 0 qsort(allWords, count, sizeof(char[][]), pstrcmp); /* int k = 0, l = 0, m = 0; char currentMax, comparedElement; int max; // the largest element in the current 2D array int elementToSort = 0; // elementToSort determines the element to swap with starting from the left // Outer a iterates through number of swaps needed for (k = 0; k < count - 1; k++) { // times of swaps max = k; // max element set to k // Inner b iterates through successive elements to fish out the largest element for (m = k + 1; m < count - k; m++) { currentMax = allWords[k][l]; comparedElement = allWords[m][l]; // Inner c iterates through successive chars to set the max vars to the largest for (l = 0; (currentMax != '\0' || comparedElement != '\0'); l++) { if (currentMax > comparedElement) break; else if (currentMax < comparedElement) { max = m; currentMax = allWords[m][l]; break; } else if (currentMax == comparedElement) continue; } } // After max (count and string) is determined, perform swap with temp variable char swapTemp[1][20]; int y = 0; do { swapTemp[0][y] = allWords[elementToSort][y]; allWords[elementToSort][y] = allWords[max][y]; allWords[max][y] = swapTemp[0][y]; } while (swapTemp[0][y++] != '\0'); elementToSort++; } */ int a, b; for (a = 0; a < count; a++) { for (b = 0; (temp = allWords[a][b]) != '\0'; b++) { printf ("%c", temp); } printf ("\n"); } // Copy rows to different array and print results /* char arrayCopy [count][20]; int ac, ad; char tempa; for (ac = 0; ac < count; ac++) { for (ad = 0; (tempa = allWords[ac][ad]) != '\0'; ad++) { arrayCopy[ac][ad] = tempa; printf("%c", arrayCopy[ac][ad]); } printf("\n"); } */ /* Step 5: Create two additional arrays: (a) One in which each element contains unique words from char array (b) One which holds the count for the corresponding word in the other array */ /* Step 6: Sort the count array in decreasing order, and print the corresponding array element as well as word count in the console */ return 0; } // Perform housekeeping tasks like freeing up memory and closing file I'm really stuck on the selection sort algorithm. I'm currently using 2D arrays to represent strings, and that worked out fine, but when it came to sorting, using three level nested loops didn't seem to work, I tried to use qsort instead, but I don't fully understand that function as well. Constructive feedback and criticism greatly welcome (...and needed)!

    Read the article

  • Cache Simulator in C

    - by DuffDuff
    Ok this is only my second question, and it's quite a doozy. It's for a school assignment, but no one (including the TAs) seems to be able to help me. It's kind of a tall order but I'm not sure where else to turn. Essentially the assignment was to make a cache simulator. This version is direct mapping and is actually only a small portion of the whole project, but if I can't even get this down I have no chance with other associativities. I'm posting my whole code because I don't want to make any assumptions about where the problem is. This is the test case: http://www.mediafire.com/?ty5dnihydnw And you run the following command: ./sims 512 direct 32 fifo wt pinatrace.out You're supposed to get: hits: 604037 misses 138349 writes: 239269 reads: 138349 But I get: Hits: 587148 Misses: 155222 Writes: 239261 Reads: 155222 If anyone could at least point me in the right direction it would be greatly appreciated. I've been stuck on this for about 12 hours. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> struct myCache { int valid; char *tag; char *block; }; /* sim [-h] <cache size> <associativity> <block size> <replace alg> <write policy> <trace file> */ //God willing I come up with a better Hex to Bin convertion that maintains the beginning 0s... void hex2bin(char input[], char output[]) { int i; int a = 0; int b = 1; int c = 2; int d = 3; int x = 4; int size; size = strlen(input); for (i = 0; i < size; i++) { if (input[i] =='0') { output[i*x +a] = '0'; output[i*x +b] = '0'; output[i*x +c] = '0'; output[i*x +d] = '0'; } else if (input[i] =='1') { output[i*x +a] = '0'; output[i*x +b] = '0'; output[i*x +c] = '0'; output[i*x +d] = '1'; } else if (input[i] =='2') { output[i*x +a] = '0'; output[i*x +b] = '0'; output[i*x +c] = '1'; output[i*x +d] = '0'; } else if (input[i] =='3') { output[i*x +a] = '0'; output[i*x +b] = '0'; output[i*x +c] = '1'; output[i*x +d] = '1'; } else if (input[i] =='x') { output[i*x +a] = '0'; output[i*x +b] = '1'; output[i*x +c] = '0'; output[i*x +d] = '0'; } else if (input[i] =='5') { output[i*x +a] = '0'; output[i*x +b] = '1'; output[i*x +c] = '0'; output[i*x +d] = '1'; } else if (input[i] =='6') { output[i*x +a] = '0'; output[i*x +b] = '1'; output[i*x +c] = '1'; output[i*x +d] = '0'; } else if (input[i] =='7') { output[i*x +a] = '0'; output[i*x +b] = '1'; output[i*x +c] = '1'; output[i*x +d] = '1'; } else if (input[i] =='8') { output[i*x +a] = '1'; output[i*x +b] = '0'; output[i*x +c] = '0'; output[i*x +d] = '0'; } else if (input[i] =='9') { output[i*x +a] = '1'; output[i*x +b] = '0'; output[i*x +c] = '0'; output[i*x +d] = '1'; } else if (input[i] =='a') { output[i*x +a] = '1'; output[i*x +b] = '0'; output[i*x +c] = '1'; output[i*x +d] = '0'; } else if (input[i] =='b') { output[i*x +a] = '1'; output[i*x +b] = '0'; output[i*x +c] = '1'; output[i*x +d] = '1'; } else if (input[i] =='c') { output[i*x +a] = '1'; output[i*x +b] = '1'; output[i*x +c] = '0'; output[i*x +d] = '0'; } else if (input[i] =='d') { output[i*x +a] = '1'; output[i*x +b] = '1'; output[i*x +c] = '0'; output[i*x +d] = '1'; } else if (input[i] =='e') { output[i*x +a] = '1'; output[i*x +b] = '1'; output[i*x +c] = '1'; output[i*x +d] = '0'; } else if (input[i] =='f') { output[i*x +a] = '1'; output[i*x +b] = '1'; output[i*x +c] = '1'; output[i*x +d] = '1'; } } output[32] = '\0'; } int main(int argc, char* argv[]) { FILE *tracefile; char readwrite; int trash; int cachesize; int blocksize; int setnumber; int blockbytes; int setbits; int blockbits; int tagsize; int m; int count = 0; int count2 = 0; int count3 = 0; int i; int j; int xindex; int jindex; int kindex; int lindex; int setadd; int totalset; int writeMiss = 0; int writeHit = 0; int cacheMiss = 0; int cacheHit = 0; int read = 0; int write = 0; int size; int extra; char bbits[100]; char sbits[100]; char tbits[100]; char output[100]; char input[100]; char origtag[100]; if (argc != 7) { if (strcmp(argv[0], "-h")) { printf("./sim2 <cache size> <associativity> <block size> <replace alg> <write policy> <trace file>\n"); return 0; } else { fprintf(stderr, "Error: wrong number of parameters.\n"); return -1; } } tracefile = fopen(argv[6], "r"); if(tracefile == NULL) { fprintf(stderr, "Error: File is NULL.\n"); return -1; } //Determining size of sbits, bbits, and tag cachesize = atoi(argv[1]); blocksize = atoi(argv[3]); setnumber = (cachesize/blocksize); printf("setnumber: %d\n", setnumber); setbits = (round((log(setnumber))/(log(2)))); printf("sbits: %d\n", setbits); blockbits = log(blocksize)/log(2); printf("bbits: %d\n", blockbits); tagsize = 32 - (blockbits + setbits); printf("t: %d\n", tagsize); struct myCache newCache[setnumber]; //Allocating Space for Tag Bits, initiating tag and valid to 0s for(i=0;i<setnumber;i++) { newCache[i].tag = (char *)malloc(sizeof(char)*(tagsize+1)); for(j=0;j<tagsize;j++) { newCache[i].tag[j] = '0'; } newCache[i].valid = 0; } while(fgetc(tracefile)!='#') { setadd = 0; totalset = 0; //read in file fseek(tracefile,-1,SEEK_CUR); fscanf(tracefile, "%x: %c %s\n", &trash, &readwrite, origtag); //shift input Hex size = strlen(origtag); extra = (10 - size); for(i=0; i<extra; i++) input[i] = '0'; for(i=extra, j=0; i<(size-(2-extra)); j++, i++) input[i]=origtag[j+2]; input[8] = '\0'; // Convert Hex to Binary hex2bin(input, output); //Resolving the Address into tbits, sbits, bbits for (xindex=0, jindex=(32-blockbits); jindex<32; jindex++, xindex++) { bbits[xindex] = output[jindex]; } bbits[xindex]='\0'; for (xindex=0, kindex=(32-(blockbits+setbits)); kindex<32-(blockbits); kindex++, xindex++){ sbits[xindex] = output[kindex]; } sbits[xindex]='\0'; for (xindex=0, lindex=0; lindex<(32-(blockbits+setbits)); lindex++, xindex++){ tbits[xindex] = output[lindex]; } tbits[xindex]='\0'; //Convert set bits from char array into ints for(xindex = 0, kindex = (setbits -1); xindex < setbits; xindex ++, kindex--) { if (sbits[xindex] == '1') setadd = 1; if (sbits[xindex] == '0') setadd = 0; setadd = setadd * pow(2, kindex); totalset += setadd; } //Calculating Hits and Misses if (newCache[totalset].valid == 0) { newCache[totalset].valid = 1; strcpy(newCache[totalset].tag, tbits); } else if (newCache[totalset].valid == 1) { if(strcmp(newCache[totalset].tag, tbits) == 0) { if (readwrite == 'W') { cacheHit++; write++; } if (readwrite == 'R') cacheHit++; } else { if (readwrite == 'R') { cacheMiss++; read++; } if (readwrite == 'W') { cacheMiss++; read++; write++; } strcpy(newCache[totalset].tag, tbits); } } } printf("Hits: %d\n", cacheHit); printf("Misses: %d\n", cacheMiss); printf("Writes: %d\n", write); printf("Reads: %d\n", read); }

    Read the article

  • Why does C qicksort function implementation works much slower (tape comparations, tape swapping) than bobble sort function?

    - by Artur Mustafin
    I'm going to implement a toy tape "mainframe" for a students, showing the quickness of "quicksort" class functions (recursive or not, does not really matters, due to the slow hardware, and well known stack reversal techniques) comparatively to the "bubblesort" function class, so, while I'm clear about the hardware implementation ans controllers, i guessed that quicksort function is much faster that other ones in terms of sequence, order and comparation distance (it is much faster to rewind the tape from the middle than from the very end, because of different speed of rewind). Unfortunately, this is not the true, this simple "bubble" code shows great improvements comparatively to the "quicksort" functions in terms of comparison distances, direction and number of comparisons and writes. So I have 3 questions: Does I have mistaken in my implememtation of quicksort function? Does I have mistaken in my implememtation of bubblesoft function? If not, why the "bubblesort" function is works much faster in (comparison and write operations) than "quicksort" function? I already have a "quicksort" function: void quicksort(float *a, long l, long r, const compare_function& compare) { long i=l, j=r, temp, m=(l+r)/2; if (l == r) return; if (l == r-1) { if (compare(a, l, r)) { swap(a, l, r); } return; } if (l < r-1) { while (1) { i = l; j = r; while (i < m && !compare(a, i, m)) i++; while (m < j && !compare(a, m, j)) j--; if (i >= j) { break; } swap(a, i, j); } if (l < m) quicksort(a, l, m, compare); if (m < r) quicksort(a, m, r, compare); return; } } and the kind of my own implememtation of the "bubblesort" function: void bubblesort(float *a, long l, long r, const compare_function& compare) { long i, j, k; if (l == r) { return; } if (l == r-1) { if (compare(a, l, r)) { swap(a, l, r); } return; } if (l < r-1) { while(l < r) { i = l; j = l; while (i < r) { i++; if (!compare(a, j, i)) { continue; } j = i; } if (l < j) { swap(a, l, j); } l++; i = r; k = r; while(l < i) { i--; if (!compare(a, i, k)) { continue; } k = i; } if (k < r) { swap(a, k, r); } r--; } return; } } I have used this sort functions in a test sample code, like this: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <conio.h> long swap_count; long compare_count; typedef long (*compare_function)(float *, long, long ); typedef void (*sort_function)(float *, long , long , const compare_function& ); void init(float *, long ); void print(float *, long ); void sort(float *, long, const sort_function& ); void swap(float *a, long l, long r); long less(float *a, long l, long r); long greater(float *a, long l, long r); void bubblesort(float *, long , long , const compare_function& ); void quicksort(float *, long , long , const compare_function& ); void main() { int n; printf("n="); scanf("%d",&n); printf("\r\n"); long i; float *a = (float *)malloc(n*n*sizeof(float)); sort(a, n, &bubblesort); print(a, n); sort(a, n, &quicksort); print(a, n); free(a); } long less(float *a, long l, long r) { compare_count++; return *(a+l) < *(a+r) ? 1 : 0; } long greater(float *a, long l, long r) { compare_count++; return *(a+l) > *(a+r) ? 1 : 0; } void swap(float *a, long l, long r) { swap_count++; float temp; temp = *(a+l); *(a+l) = *(a+r); *(a+r) = temp; } float tg(float x) { return tan(x); } float ctg(float x) { return 1.0/tan(x); } void init(float *m,long n) { long i,j; for (i = 0; i < n; i++) { for (j=0; j< n; j++) { m[i + j*n] = tg(0.2*(i+1)) + ctg(0.3*(j+1)); } } } void print(float *m, long n) { long i, j; for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { printf(" %5.1f", m[i + j*n]); } printf("\r\n"); } printf("\r\n"); } void sort(float *a, long n, const sort_function& sort) { long i, sort_compare = 0, sort_swap = 0; init(a,n); for(i = 0; i < n*n; i+=n) { if (fmod (i / n, 2) == 0) { compare_count = 0; swap_count = 0; sort(a, i, i+n-1, &less); if (swap_count == 0) { compare_count = 0; sort(a, i, i+n-1, &greater); } sort_compare += compare_count; sort_swap += swap_count; } } printf("compare=%ld\r\n", sort_compare); printf("swap=%ld\r\n", sort_swap); printf("\r\n"); }

    Read the article

  • Segmentation fault in my C program

    - by user233542
    I don't understand why this would give me a seg fault. Any ideas? This is the function that returns the signal to stop the program (plus the other function that is called within this): double bisect(double A0,double A1,double Sol[N],double tol,double c) { double Amid,shot; while (A1-A0 > tol) { Amid = 0.5*(A0+A1); shot = shoot(Sol, Amid, c); if (shot==2.*Pi) { return Amid; } if (shot > 2.*Pi){ A1 = Amid; } else if (shot < 2.*Pi){ A0 = Amid; } } return 0.5*(A1+A0); } double shoot(double Sol[N],double A,double c) { int i,j; /*Initial Conditions*/ for (i=0;i<buff;i++) { Sol[i] = 0.; } for (i=buff+l;i<N;i++) { Sol[i] = 2.*Pi; } Sol[buff]= 0; Sol[buff+1]= A*exp(sqrt(1+3*c)*dx); for (i=buff+2;i<buff+l;i++) { Sol[i] = (dx*dx)*( sin(Sol[i-1]) + c*sin(3.*(Sol[i-1])) ) - Sol[i-2] + 2.*Sol[i-1]; } return Sol[i-1]; } The values buff, l, N are defined using a #define statement. l = 401, buff = 50, N = 2000 Here is the full code: #include <stdio.h> #include <stdlib.h> #include <math.h> #define w 10 /*characteristic width of a soliton*/ #define dx 0.05 /*distance between lattice sites*/ #define s (2*w)/dx /*size of soliton shape*/ #define l (int)(s+1) /*array length for soliton*/ #define N (int)2000 /*length of field array--lattice sites*/ #define Pi (double)4*atan(1) #define buff (int)50 double shoot(double Sol[N],double A,double c); double bisect(double A0,double A1,double Sol[N],double tol,double c); void super_pos(double antiSol[N],double Sol[N],double phi[][N]); void vel_ver(double phi[][N],double v,double c,int tsteps,double dt); int main(int argc, char **argv) { double c,Sol[N],antiSol[N],A,A0,A1,tol,v,dt; int tsteps,i; FILE *fp1,*fp2,*fp3; fp1 = fopen("soliton.dat","w"); fp2 = fopen("final-phi.dat","w"); fp3 = fopen("energy.dat","w"); printf("Please input the number of time steps:"); scanf("%d",&tsteps); printf("Also, enter the time step size:"); scanf("%lf",&dt); do{ printf("Please input the parameter c in the interval [-1/3,1]:"); scanf("%lf",&c);} while(c < (-1./3.) || c > 1.); printf("Please input the inital speed of eiter soliton:"); scanf("%lf",&v); double phi[tsteps+1][N]; tol = 0.0000001; A0 = 0.; A1 = 2.*Pi; A = bisect(A0,A1,Sol,tol,c); shoot(Sol,A,c); for (i=0;i<N;i++) { fprintf(fp1,"%d\t",i); fprintf(fp1,"%lf\n",Sol[i]); } fclose(fp1); super_pos(antiSol,Sol,phi); /*vel_ver(phi,v,c,tsteps,dt); for (i=0;i<N;i++){ fprintf(fp2,"%d\t",i); fprintf(fp2,"%lf\n",phi[tsteps][i]); }*/ } double shoot(double Sol[N],double A,double c) { int i,j; /*Initial Conditions*/ for (i=0;i<buff;i++) { Sol[i] = 0.; } for (i=buff+l;i<N;i++) { Sol[i] = 2.*Pi; } Sol[buff]= 0; Sol[buff+1]= A*exp(sqrt(1+3*c)*dx); for (i=buff+2;i<buff+l;i++) { Sol[i] = (dx*dx)*( sin(Sol[i-1]) + c*sin(3.*(Sol[i-1])) ) - Sol[i-2] + 2.*Sol[i-1]; } return Sol[i-1]; } double bisect(double A0,double A1,double Sol[N],double tol,double c) { double Amid,shot; while (A1-A0 > tol) { Amid = 0.5*(A0+A1); shot = shoot(Sol, Amid, c); if (shot==2.*Pi) { return Amid; } if (shot > 2.*Pi){ A1 = Amid; } else if (shot < 2.*Pi){ A0 = Amid; } } return 0.5*(A1+A0); } void super_pos(double antiSol[N],double Sol[N],double phi[][N]) { int i; /*for (i=0;i<N;i++) { phi[i]=0; } for (i=buffer+s;i<1950-s;i++) { phi[i]=2*Pi; }*/ for (i=0;i<N;i++) { antiSol[i] = Sol[N-i]; } /*for (i=0;i<s+1;i++) { phi[buffer+j] = Sol[j]; phi[1549+j] = antiSol[j]; }*/ for (i=0;i<N;i++) { phi[0][i] = antiSol[i] + Sol[i] - 2.*Pi; } } /* This funciton will set the 2nd input array to the derivative at the time t, for all points x in the lattice */ void deriv2(double phi[][N],double DphiDx2[][N],int t) { //double SolDer2[s+1]; int x; for (x=0;x<N;x++) { DphiDx2[t][x] = (phi[buff+x+1][t] + phi[buff+x-1][t] - 2.*phi[x][t])/(dx*dx); } /*for (i=0;i<N;i++) { ptr[i] = &SolDer2[i]; }*/ //return DphiDx2[x]; } void vel_ver(double phi[][N],double v,double c,int tsteps,double dt) { int t,x; double d1,d2,dp,DphiDx1[tsteps+1][N],DphiDx2[tsteps+1][N],dpdt[tsteps+1][N],p[tsteps+1][N]; for (t=0;t<tsteps;t++){ if (t==0){ for (x=0;x<N;x++){//inital conditions deriv2(phi,DphiDx2,t); dpdt[t][x] = DphiDx2[t][x] - sin(phi[t][x]) - sin(3.*phi[t][x]); DphiDx1[t][x] = (phi[t][x+1] - phi[t][x])/dx; p[t][x] = -v*DphiDx1[t][x]; } } for (x=0;x<N;x++){//velocity-verlet phi[t+1][x] = phi[t][x] + dt*p[t][x] + (dt*dt/2)*dpdt[t][x]; p[t+1][x] = p[t][x] + (dt/2)*dpdt[t][x]; deriv2(phi,DphiDx2,t+1); dpdt[t][x] = DphiDx2[t][x] - sin(phi[t+1][x]) - sin(3.*phi[t+1][x]); p[t+1][x] += (dt/2)*dpdt[t+1][x]; } } } So, this really isn't due to my overwriting the end of the Sol array. I've commented out both functions that I suspected of causing the problem (bisect or shoot) and inserted a print function. Two things happen. When I have code like below: double A,Pi,B,c; c=0; Pi = 4.*atan(1.); A = Pi; B = 1./4.; printf("%lf",B); B = shoot(Sol,A,c); printf("%lf",B); I get a segfault from the function, shoot. However, if I take away the shoot function so that I have: double A,Pi,B,c; c=0; Pi = 4.*atan(1.); A = Pi; B = 1./4.; printf("%lf",B); it gives me a segfault at the printf... Why!?

    Read the article

  • Help with malloc and free: Glibc detected: free(): invalid pointer

    - by nunos
    I need help with debugging this piece of code. I know the problem is in malloc and free but can't find exactly where, why and how to fix it. Please don't answer: "Use gdb" and that's it. I would use gdb to debug it, but I still don't know much about it and am still learning it, and would like to have, in the meanwhile, another solution. Thanks. #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #define MAX_COMMAND_LENGTH 256 #define MAX_ARGS_NUMBER 128 #define MAX_HISTORY_NUMBER 100 #define PROMPT ">>> " int num_elems; typedef enum {false, true} bool; typedef struct { char **arg; char *infile; char *outfile; int background; } Command_Info; int parse_cmd(char *cmd_line, Command_Info *cmd_info) { char *arg; char *args[MAX_ARGS_NUMBER]; int i = 0; arg = strtok(cmd_line, " "); while (arg != NULL) { args[i] = arg; arg = strtok(NULL, " "); i++; } num_elems = i;precisa em free_mem if (num_elems == 0) return 0; cmd_info->arg = (char **) ( malloc(num_elems * sizeof(char *)) ); cmd_info->infile = NULL; cmd_info->outfile = NULL; cmd_info->background = 0; bool b_infile = false; bool b_outfile = false; int iarg = 0; for (i = 0; i < num_elems; i++) { if ( !strcmp(args[i], "<") ) { if ( b_infile || i == num_elems-1 || !strcmp(args[i+1], "<") || !strcmp(args[i+1], ">") || !strcmp(args[i+1], "&") ) return -1; i++; cmd_info->infile = malloc(strlen(args[i]) * sizeof(char)); strcpy(cmd_info->infile, args[i]); b_infile = true; } else if (!strcmp(args[i], ">")) { if ( b_outfile || i == num_elems-1 || !strcmp(args[i+1], ">") || !strcmp(args[i+1], "<") || !strcmp(args[i+1], "&") ) return -1; i++; cmd_info->outfile = malloc(strlen(args[i]) * sizeof(char)); strcpy(cmd_info->outfile, args[i]); b_outfile = true; } else if (!strcmp(args[i], "&")) { if ( i == 0 || i != num_elems-1 || cmd_info->background ) return -1; cmd_info->background = true; } else { cmd_info->arg[iarg] = malloc(strlen(args[i]) * sizeof(char)); strcpy(cmd_info->arg[iarg], args[i]); iarg++; } } cmd_info->arg[iarg] = NULL; return 0; } void print_cmd(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("infile=\"%s\"\n", cmd_info->infile); printf("outfile=\"%s\"\n", cmd_info->outfile); printf("background=\"%d\"\n", cmd_info->background); } void get_cmd(char* str) { fgets(str, MAX_COMMAND_LENGTH, stdin); str[strlen(str)-1] = '\0'; } pid_t exec_simple(Command_Info *cmd_info) { pid_t pid = fork(); if (pid < 0) { perror("Fork Error"); return -1; } if (pid == 0) { if ( (execvp(cmd_info->arg[0], cmd_info->arg)) == -1) { perror(cmd_info->arg[0]); exit(1); } } return pid; } void type_prompt(void) { printf("%s", PROMPT); } void syntax_error(void) { printf("msh syntax error\n"); } void free_mem(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) free(cmd_info->arg[i]); free(cmd_info->arg); free(cmd_info->infile); free(cmd_info->outfile); } int main(int argc, char* argv[]) { char cmd_line[MAX_COMMAND_LENGTH]; Command_Info cmd_info; //char* history[MAX_HISTORY_NUMBER]; while (true) { type_prompt(); get_cmd(cmd_line); if ( parse_cmd(cmd_line, &cmd_info) == -1) { syntax_error(); continue; } if (!strcmp(cmd_line, "")) continue; if (!strcmp(cmd_info.arg[0], "exit")) exit(0); pid_t pid = exec_simple(&cmd_info); waitpid(pid, NULL, 0); free_mem(&cmd_info); } return 0; }

    Read the article

  • Object allocations in the cellForRowAtIndexPath method is increasing? Is dealloc not called in prese

    - by Madan Mohan
    Hi Guys, This is PresentModelViewController, when click a button i will get this "DoctorListViewController" controller from down. object allocation are not releasing in this controller specially in cellForRowAtIndexPath delegate method. UITableViewCell and two labels allocated in this is not releasing. In the previous view The allocation count of this " UITableViewCell and two labels" is increasing.Also the dealloc method in this view controller is not called when I dismiss the modelviewcontrller, that is way I have released in the close method. please suggest me a right solution Thank you. import "DoctorListViewController.h" @implementation DoctorListViewController @synthesize doctorList; - (id)init { if (self = [super init]) { self.title=@"Doctors List"; UIView *myView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; myView.autoresizingMask=YES; [myView setBackgroundColor:[UIColor groupTableViewBackgroundColor]]; myTableView=nil; myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,320,420) style:UITableViewStylePlain]; myTableView.delegate = self; myTableView.dataSource=self; [myTableView setSectionFooterHeight:5]; [myTableView setSectionHeaderHeight:15]; [myTableView setSeparatorColor:[UIColor greenColor]]; [myView addSubview: myTableView]; UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithTitle:@"Close" style:UIBarButtonItemStyleBordered target:self action:@selector(closeAction)]; self.navigationItem.leftBarButtonItem = addButton; [addButton release]; self.view = myView; [myView release]; } return self; } -(void)viewWillAppear:(BOOL)animated { DoctorsAppDelegate *appDelegate = (DoctorsAppDelegate *) [ [UIApplication sharedApplication] delegate]; [self setToPortrait:appDelegate.isPortrait]; } -(void)setToPortrait:(BOOL)isPortrait { if(isPortrait == YES) { printf("\n hai i am in setToPortrait method"); [self shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationPortrait]; } } -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { DoctorsAppDelegate *appDelegate = (DoctorsAppDelegate *) [ [UIApplication sharedApplication] delegate]; if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight ) { myTableView.frame=CGRectMake(0,0,480,265); appDelegate.isPortrait=NO; } else if(interfaceOrientation == UIInterfaceOrientationPortrait) { myTableView.frame=CGRectMake(0,0,320,415); appDelegate.isPortrait=YES; } return YES; } -(void)closeAction { printf("\n hai i am in close action*****************"); [doctorList release]; [myTableView release]; myTableView=nil; printf("\n myTableView retainCount :%d",[myTableView retainCount]); [[self navigationController] dismissModalViewControllerAnimated:YES]; } pragma mark methods for dataSource and delegate (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } (NSInteger)tableView:(UITableView )tableView numberOfRowsInSection:(NSInteger)section { / int numberOfRows = [doctorList count]; if(numberOfRows =[doctorList count]){ numberOfRows++; } return numberOfRows; */ return [doctorList count]; } (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 50; } (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = (UITableViewCell *)[myTableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"MyIdentifier"]autorelease]; UIView* elementView = [ [UIView alloc] initWithFrame:CGRectMake(5,5,300,480)]; elementView.tag = 0; [cell.contentView addSubview:elementView]; [elementView release]; } UIView* elementView = [cell.contentView viewWithTag:0]; for(UIView* subView in elementView.subviews) { [subView removeFromSuperview]; } if(indexPath.row != [doctorList count]) { cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; Doctor *obj= [doctorList objectAtIndex:indexPath.row]; UILabel *firstNameLabel =[[[UILabel alloc] initWithFrame:CGRectMake(5,2,300,15)]autorelease]; [firstNameLabel setFont:[UIFont boldSystemFontOfSize:12]]; firstNameLabel.textColor = [UIColor blackColor]; firstNameLabel.textColor =[UIColor blackColor]; firstNameLabel.numberOfLines = 0; firstNameLabel.tag=1; firstNameLabel.backgroundColor = [UIColor clearColor]; NSString *str=obj.firstName; str=[str stringByAppendingString:@" "]; str=[str stringByAppendingString:obj.lastName]; firstNameLabel.text=str; [elementView addSubview:firstNameLabel]; //[firstNameLabel release]; firstNameLabel=nil; UILabel *streetLabel =[[[UILabel alloc] initWithFrame:CGRectMake(5,20,300,15)]autorelease]; [streetLabel setFont:[UIFont systemFontOfSize:12]]; streetLabel.textColor = [UIColor blackColor]; streetLabel.numberOfLines = 0; streetLabel.tag=2; streetLabel.backgroundColor = [UIColor clearColor]; streetLabel.text=obj.streetAddress; [elementView addSubview:streetLabel]; //[streetLabel release]; streetLabel=nil; printf("\n retainCount count of firstNameLabel %d",[firstNameLabel retainCount]); printf("\n retainCount count of streetLabel %d",[streetLabel retainCount]); printf("\n retainCount count of cell %d",[cell retainCount]); } return cell; } (void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [myTableView deselectRowAtIndexPath:indexPath animated:YES]; DoctorDetailsViewController *doctorDetailsViewController=[[DoctorDetailsViewController alloc]init]; Doctor *obj= [doctorList objectAtIndex:indexPath.row]; BOOL isList=YES; doctorDetailsViewController.isList=isList; doctorDetailsViewController.doctorObj=obj; [[self navigationController] pushViewController:doctorDetailsViewController animated:YES]; [doctorDetailsViewController release]; } (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } (void)dealloc { printf("\n hai i am in dealloc of Doctor list view contrller"); //[doctorList release]; //[myTableView release]; [super dealloc]; } @end

    Read the article

  • "The usage of semaphores is subtly wrong"

    - by Hoonose
    This past semester I was taking an OS practicum in C, in which the first project involved making a threads package, then writing a multiple producer-consumer program to demonstrate the functionality. However, after getting grading feedback, I lost points for "The usage of semaphores is subtly wrong" and "The program assumes preemption (e.g. uses yield to change control)" (We started with a non-preemptive threads package then added preemption later. Note that the comment and example contradict each other. I believe it doesn't assume either, and would work in both environments). This has been bugging me for a long time - the course staff was kind of overwhelmed, so I couldn't ask them what's wrong with this over the semester. I've spent a long time thinking about this and I can't see the issues. If anyone could take a look and point out the error, or reassure me that there actually isn't a problem, I'd really appreciate it. I believe the syntax should be pretty standard in terms of the thread package functions (minithreads and semaphores), but let me know if anything is confusing. #include <stdio.h> #include <stdlib.h> #include "minithread.h" #include "synch.h" #define BUFFER_SIZE 16 #define MAXCOUNT 100 int buffer[BUFFER_SIZE]; int size, head, tail; int count = 1; int out = 0; int toadd = 0; int toremove = 0; semaphore_t empty; semaphore_t full; semaphore_t count_lock; // Semaphore to keep a lock on the // global variables for maintaining the counts /* Method to handle the working of a student * The ID of a student is the corresponding minithread_id */ int student(int total_burgers) { int n, i; semaphore_P(count_lock); while ((out+toremove) < arg) { n = genintrand(BUFFER_SIZE); n = (n <= total_burgers - (out + toremove)) ? n : total_burgers - (out + toremove); printf("Student %d wants to get %d burgers ...\n", minithread_id(), n); toremove += n; semaphore_V(count_lock); for (i=0; i<n; i++) { semaphore_P(empty); out = buffer[tail]; printf("Student %d is taking burger %d.\n", minithread_id(), out); tail = (tail + 1) % BUFFER_SIZE; size--; toremove--; semaphore_V(full); } semaphore_P(count_lock); } semaphore_V(count_lock); printf("Student %d is done.\n", minithread_id()); return 0; } /* Method to handle the working of a cook * The ID of a cook is the corresponding minithread_id */ int cook(int total_burgers) { int n, i; printf("Creating Cook %d\n",minithread_id()); semaphore_P(count_lock); while ((count+toadd) <= arg) { n = genintrand(BUFFER_SIZE); n = (n <= total_burgers - (count + toadd) + 1) ? n : total_burgers - (count + toadd) + 1; printf("Cook %d wants to put %d burgers into the burger stack ...\n", minithread_id(),n); toadd += n; semaphore_V(count_lock); for (i=0; i<n; i++) { semaphore_P(full); printf("Cook %d is putting burger %d into the burger stack.\n", minithread_id(), count); buffer[head] = count++; head = (head + 1) % BUFFER_SIZE; size++; toadd--; semaphore_V(empty); } semaphore_P(count_lock); } semaphore_V(count_lock); printf("Cook %d is done.\n", minithread_id()); return 0; } /* Method to create our multiple producers and consumers * and start their respective threads by fork */ void starter(int* c){ int i; for (i=0;i<c[2];i++){ minithread_fork(cook, c[0]); } for (i=0;i<c[1];i++){ minithread_fork(student, c[0]); } } /* The arguments are passed as command line parameters * argv[1] is the no of students * argv[2] is the no of cooks */ void main(int argc, char *argv[]) { int pass_args[3]; pass_args[0] = MAXCOUNT; pass_args[1] = atoi(argv[1]); pass_args[2] = atoi(argv[2]); size = head = tail = 0; empty = semaphore_create(); semaphore_initialize(empty, 0); full = semaphore_create(); semaphore_initialize(full, BUFFER_SIZE); count_lock = semaphore_create(); semaphore_initialize(count_lock, 1); minithread_system_initialize(starter, pass_args); }

    Read the article

  • a program similar to ls with some modifications

    - by Bond
    Hi, here is a simple puzzle I wanted to discuss. A C program to take directory name as command line argument and print last 3 directories and 3 files in all subdirectories without using api 'system' inside it. suppose directory bond0 contains bond1, di2, bond3, bond4, bond5 and my_file1, my_file2, my_file3, my_file4, my_file5, my_file6 and bond1 contains bond6 my_file7 my_file8 my_file9 my_file10 program should output - bond3, bond4, bond5, my_file4, my_file5, my_file6, bond6, my_file8, my_file9, my_file10 My code for the above problem is here #include<dirent.h> #include<unistd.h> #include<string.h> #include<sys/stat.h> #include<stdlib.h> #include<stdio.h> char *directs[20], *files[20]; int i = 0; int j = 0; int count = 0; void printdir(char *); int count_dirs(char *); int count_files(char *); int main() { char startdir[20]; printf("Scanning user directories\n"); scanf("%s", startdir); printdir(startdir); } void printdir(char *dir) { printf("printdir called %d directory is %s\n", ++count, dir); DIR *dp = opendir(dir); int nDirs, nFiles, nD, nF; nDirs = 0; nFiles = 0; nD = 0; nF = 0; if (dp) { struct dirent *entry = 0; struct stat statBuf; nDirs = count_dirs(dir); nFiles = count_files(dir); printf("The no of subdirectories in %s is %d \n", dir, nDirs); printf("The no of files in %s is %d \n", dir, nFiles); while ((entry = readdir(dp)) != 0) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } char *filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2); if (filepath) { sprintf(filepath, "%s/%s", dir, entry->d_name); if (lstat(filepath, &statBuf) != 0) { } if (S_ISDIR(statBuf.st_mode)) { nD++; if ((nDirs - nD) < 3) { printf("The directory is %s\n",entry->d_name); } } else { nF++; if ((nFiles - nF) < 3) { printf("The files are %s\n", entry->d_name); } //if } //else free(filepath); } //if(filepath) } //while while ((entry = readdir(dp)) != 0) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } printf("In second while loop *entry=%s\n",entry->d_name); char *filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2); if (filepath) { sprintf(filepath, "%s/%s", dir, entry->d_name); if (lstat(filepath, &statBuf) != 0) { } if (S_ISDIR(statBuf.st_mode)) { printdir(entry->d_name); } } //else free(filepath); } //2nd while closedir(dp); } else { fprintf(stderr, "Error, cannot open directory %s\n", dir); } } //printdir int count_dirs(char *dir) { DIR *dp = opendir(dir); int nD; nD = 0; if (dp) { struct dirent *entry = 0; struct stat statBuf; while ((entry = readdir(dp)) != 0) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } char *filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2); if (filepath) { sprintf(filepath, "%s/%s", dir, entry->d_name); if (lstat(filepath, &statBuf) != 0) { fprintf(stderr, "File Not found? %s\n", filepath); } if (S_ISDIR(statBuf.st_mode)) { nD++; } else { continue; } free(filepath); } } closedir(dp); } else { fprintf(stderr, "Error, cannot open directory %s\n", dir); } return nD; } int count_files(char *dir) { DIR *dp = opendir(dir); int nF; nF = 0; if (dp) { struct dirent *entry = 0; struct stat statBuf; while ((entry = readdir(dp)) != 0) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } char *filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2); if (filepath) { sprintf(filepath, "%s/%s", dir, entry->d_name); if (lstat(filepath, &statBuf) != 0) { fprintf(stderr, "File Not found? %s\n", filepath); } if (S_ISDIR(statBuf.st_mode)) { continue; } else { nF++; } free(filepath); } } closedir(dp); } else { fprintf(stderr, "Error, cannot open file %s\n", dir); } return nF; } The above code I wrote is a bit not functioning correctly can some one help me to understand the error which is coming.So that I improve it further.There seems to be some small glitch which is not clear to me right now.

    Read the article

  • Elapsed time of running a C program

    - by yCalleecharan
    Hi, I would like to know what lines of C code to add to a program so that it tells me the total time that the program takes to run. I guess there should be counter initialization near the beginning of main and one after the main function ends. Is the right header clock.h? Thanks a lot... Update I have a Win Xp machine. Is it just adding clock() at the beginning and another clock() at the end of the program? Then I can estimate the time difference. Yes, you're right it's time.h. Here's my code: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <share.h> #include <time.h> void f(long double fb[], long double fA, long double fB); int main() { clock_t start, end; start = clock(); const int ARRAY_SIZE = 11; long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE); int i; long double A, B; if (z == NULL) { printf("Out of memory\n"); exit(-1); } A = 0.5; B = 2; for (i = 0; i < ARRAY_SIZE; i++) { z[i] = 0; } z[1] = 5; f(z, A, B); for (i = 0; i < ARRAY_SIZE; i++) printf("z is %.16Le\n", z[i]); free(z); z = NULL; end = clock(); printf("Took %ld ticks\n", end-start); printf("Took %f seconds\n", (double)(end-start)/CLOCKS_PER_SEC); return 0; } void f(long double fb[], long double fA, long double fB) { fb[0] = fb[1]* fA; fb[1] = fb[1] - 1; return; } Some errors with MVS2008: testim.c(16) : error C2143: syntax error : missing ';' before 'const' testim.c(18) :error C2143: syntax error : missing ';' before 'type' testim.c(20) :error C2143: syntax error : missing ';' before 'type' testim.c(21) :error C2143: syntax error : missing ';' before 'type' testim.c(23) :error C2065: 'z' : undeclared identifier testim.c(23) :warning C4047: '==' : 'int' differs in levels of indirection from 'void *' testim.c(28) : error C2065: 'A' : undeclared identifier testim.c(28) : warning C4244: '=' : conversion from 'double' to 'int', possible loss of data and it goes to 28 errors. Note that I don't have any errors/warnings without your clock codes. LATEST NEWS: I unfortunately didn't get a good reply here. But after a search on Google, the code is working. Here it is: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <share.h> #include <time.h> void f(long double fb[], long double fA, long double fB); int main() { clock_t start = clock(); const int ARRAY_SIZE = 11; long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE); int i; long double A, B; if (z == NULL) { printf("Out of memory\n"); exit(-1); } A = 0.5; B = 2; for (i = 0; i < ARRAY_SIZE; i++) { z[i] = 0; } z[1] = 5; f(z, A, B); for (i = 0; i < ARRAY_SIZE; i++) printf("z is %.16Le\n", z[i]); free(z); z = NULL; printf("Took %f seconds\n", ((double)clock()-start)/CLOCKS_PER_SEC); return 0; } void f(long double fb[], long double fA, long double fB) { fb[0] = fb[1]* fA; fb[1] = fb[1] - 1; return; } Cheers

    Read the article

  • what is the wrong in this code(openAl in vc++)

    - by maiajam
    hi how are you all? i need your help i have this code #include <conio.h> #include <stdlib.h> #include <stdio.h> #include <al.h> #include <alc.h> #include <alut.h> #pragma comment(lib, "openal32.lib") #pragma comment(lib, "alut.lib") /* * These are OpenAL "names" (or "objects"). They store and id of a buffer * or a source object. Generally you would expect to see the implementation * use values that scale up from '1', but don't count on it. The spec does * not make this mandatory (as it is OpenGL). The id's can easily be memory * pointers as well. It will depend on the implementation. */ // Buffers to hold sound data. ALuint Buffer; // Sources are points of emitting sound. ALuint Source; /* * These are 3D cartesian vector coordinates. A structure or class would be * a more flexible of handling these, but for the sake of simplicity we will * just leave it as is. */ // Position of the source sound. ALfloat SourcePos[] = { 0.0, 0.0, 0.0 }; // Velocity of the source sound. ALfloat SourceVel[] = { 0.0, 0.0, 0.0 }; // Position of the Listener. ALfloat ListenerPos[] = { 0.0, 0.0, 0.0 }; // Velocity of the Listener. ALfloat ListenerVel[] = { 0.0, 0.0, 0.0 }; // Orientation of the Listener. (first 3 elements are "at", second 3 are "up") // Also note that these should be units of '1'. ALfloat ListenerOri[] = { 0.0, 0.0, -1.0, 0.0, 1.0, 0.0 }; /* * ALboolean LoadALData() * * This function will load our sample data from the disk using the Alut * utility and send the data into OpenAL as a buffer. A source is then * also created to play that buffer. */ ALboolean LoadALData() { // Variables to load into. ALenum format; ALsizei size; ALvoid* data; ALsizei freq; ALboolean loop; // Load wav data into a buffer. alGenBuffers(1, &Buffer); if(alGetError() != AL_NO_ERROR) return AL_FALSE; alutLoadWAVFile((ALbyte *)"C:\Users\Toshiba\Desktop\Graduation Project\OpenAL\open AL test\wavdata\FancyPants.wav", &format, &data, &size, &freq, &loop); alBufferData(Buffer, format, data, size, freq); alutUnloadWAV(format, data, size, freq); // Bind the buffer with the source. alGenSources(1, &Source); if(alGetError() != AL_NO_ERROR) return AL_FALSE; alSourcei (Source, AL_BUFFER, Buffer ); alSourcef (Source, AL_PITCH, 1.0 ); alSourcef (Source, AL_GAIN, 1.0 ); alSourcefv(Source, AL_POSITION, SourcePos); alSourcefv(Source, AL_VELOCITY, SourceVel); alSourcei (Source, AL_LOOPING, loop ); // Do another error check and return. if(alGetError() == AL_NO_ERROR) return AL_TRUE; return AL_FALSE; } /* * void SetListenerValues() * * We already defined certain values for the Listener, but we need * to tell OpenAL to use that data. This function does just that. */ void SetListenerValues() { alListenerfv(AL_POSITION, ListenerPos); alListenerfv(AL_VELOCITY, ListenerVel); alListenerfv(AL_ORIENTATION, ListenerOri); } /* * void KillALData() * * We have allocated memory for our buffers and sources which needs * to be returned to the system. This function frees that memory. */ void KillALData() { alDeleteBuffers(1, &Buffer); alDeleteSources(1, &Source); alutExit(); } int main(int argc, char *argv[]) { printf("MindCode's OpenAL Lesson 1: Single Static Source\n\n"); printf("Controls:\n"); printf("p) Play\n"); printf("s) Stop\n"); printf("h) Hold (pause)\n"); printf("q) Quit\n\n"); // Initialize OpenAL and clear the error bit. alutInit(NULL, 0); alGetError(); // Load the wav data. if(LoadALData() == AL_FALSE) { printf("Error loading data."); return 0; } SetListenerValues(); // Setup an exit procedure. atexit(KillALData); // Loop. ALubyte c = ' '; while(c != 'q') { c = getche(); switch(c) { // Pressing 'p' will begin playing the sample. case 'p': alSourcePlay(Source); break; // Pressing 's' will stop the sample from playing. case 's': alSourceStop(Source); break; // Pressing 'h' will pause the sample. case 'h': alSourcePause(Source); break; }; } return 0; } and it is run willbut i cant here any thing also i am new in programong and wont to program a virtual reality sound in my graduation project and start to learn opeal and vc++ but i dont how to start and from where i must begin and i want to ask if i need to learn about API win ?? and if i need how i can learn that thank you alote and i am sorry coz of my english

    Read the article

  • Binary Tree in C Insertion Error

    - by Paul
    I'm quite new to C and I'm trying to implement a Binary Tree in C which will store a number and a string and then print them off e.g. 1 : Bread 2 : WashingUpLiquid etc. The code I have so far is: #include <stdio.h> #include <stdlib.h> #define LENGTH 300 struct node { int data; char * definition; struct node *left; struct node *right; }; struct node *node_insert(struct node *p, int value, char * word); void print_preorder(struct node *p); int main(void) { int i = 0; int d = 0; char def[LENGTH]; struct node *root = NULL; for(i = 0; i < 2; i++) { printf("Please enter a number: \n"); scanf("%d", &d); printf("Please enter a definition for this word:\n"); scanf("%s", def); root = node_insert(root, d, def); printf("%s\n", def); } printf("preorder : "); print_preorder(root); printf("\n"); return 0; } struct node *node_insert(struct node *p, int value, char * word) { struct node *tmp_one = NULL; struct node *tmp_two = NULL; if(p == NULL) { p = (struct node *)malloc(sizeof(struct node)); p->data = value; p->definition = word; p->left = p->right = NULL; } else { tmp_one = p; while(tmp_one != NULL) { tmp_two = tmp_one; if(tmp_one->data > value) tmp_one = tmp_one->left; else tmp_one = tmp_one->right; } if(tmp_two->data > value) { tmp_two->left = (struct node *)malloc(sizeof(struct node)); tmp_two = tmp_two->left; tmp_two->data = value; tmp_two->definition = word; tmp_two->left = tmp_two->right = NULL; } else { tmp_two->right = (struct node *)malloc(sizeof(struct node)); tmp_two = tmp_two->right; tmp_two->data = value; tmp_two->definition = word; tmp_two->left = tmp_two->right = NULL; } } return(p); } void print_preorder(struct node *p) { if(p != NULL) { printf("%d : %s\n", p->data, p->definition); print_preorder(p->left); print_preorder(p->right); } } At the moment it seems to work for the ints but the description part only prints out for the last one entered. I assume it has something to do with pointers on the char array but I had no luck getting it to work. Any ideas or advice? Thanks

    Read the article

  • CPU Affinity Masks (Putting Threads on different CPUs)

    - by hahuang65
    I have 4 threads, and I am trying to set thread 1 to run on CPU 1, thread 2 on CPU 2, etc. However, when I run my code below, the affinity masks are returning the correct values, but when I do a sched_getcpu() on the threads, they all return that they are running on CPU 4. Anybody know what my problem here is? Thanks in advance! #define _GNU_SOURCE #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <sched.h> #include <errno.h> void *pthread_Message(char *message) { printf("%s is running on CPU %d\n", message, sched_getcpu()); } int main() { pthread_t thread1, thread2, thread3, thread4; pthread_t threadArray[4]; cpu_set_t cpu1, cpu2, cpu3, cpu4; char *thread1Msg = "Thread 1"; char *thread2Msg = "Thread 2"; char *thread3Msg = "Thread 3"; char *thread4Msg = "Thread 4"; int thread1Create, thread2Create, thread3Create, thread4Create, i, temp; CPU_ZERO(&cpu1); CPU_SET(1, &cpu1); temp = pthread_setaffinity_np(thread1, sizeof(cpu_set_t), &cpu1); printf("Set returned by pthread_getaffinity_np() contained:\n"); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu1)) printf("CPU1: CPU %d\n", i); CPU_ZERO(&cpu2); CPU_SET(2, &cpu2); temp = pthread_setaffinity_np(thread2, sizeof(cpu_set_t), &cpu2); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu2)) printf("CPU2: CPU %d\n", i); CPU_ZERO(&cpu3); CPU_SET(3, &cpu3); temp = pthread_setaffinity_np(thread3, sizeof(cpu_set_t), &cpu3); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu3)) printf("CPU3: CPU %d\n", i); CPU_ZERO(&cpu4); CPU_SET(4, &cpu4); temp = pthread_setaffinity_np(thread4, sizeof(cpu_set_t), &cpu4); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu4)) printf("CPU4: CPU %d\n", i); thread1Create = pthread_create(&thread1, NULL, (void *)pthread_Message, thread1Msg); thread2Create = pthread_create(&thread2, NULL, (void *)pthread_Message, thread2Msg); thread3Create = pthread_create(&thread3, NULL, (void *)pthread_Message, thread3Msg); thread4Create = pthread_create(&thread4, NULL, (void *)pthread_Message, thread4Msg); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); pthread_join(thread4, NULL); return 0; }

    Read the article

  • Socket in C: recv overwrite a char[]

    - by Possa
    Hi all, I'm trying to make a little client-server script like many others that I've done in the past. But in this one I have a problem. It is better if I post the code and the output it give me. Code: #include <mysql.h> //not important now #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <string.h> //constant definition #define SERVER_PORT 2121 #define LINESIZE 21 //global var definition char victim_ip[LINESIZE], file_write[LINESIZE], hacker_ip[LINESIZE]; //function void leggi (int); //not use now for debugging purpose //void scriviDB (); //not important now main () { int sock, client_len, fd; struct sockaddr_in server, client; // transport end point if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("system call socket fail"); exit(1); } server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr("10.10.10.1"); server.sin_port = htons(SERVER_PORT); // binding address at transport end point if (bind(sock, (struct sockaddr *)&server, sizeof server) == -1) { perror("system call bind fail"); exit(1); } //fprintf(stderr, "Server open: listening.\n"); listen(sock, 5); /* managae client connection */ while (1) { client_len = sizeof(client); if ((fd = accept(sock, (struct sockaddr *)&client, &client_len)) < 0) { perror("accepting connection"); exit(1); } strcpy(hacker_ip, inet_ntoa(client.sin_addr)); printf("1 %s\n", hacker_ip); //debugging purpose //leggi(fd); ////////////////////////// //receive client recv(fd, victim_ip, LINESIZE, 0); victim_ip[sizeof(victim_ip)] = '\0'; printf("2 %s\n", hacker_ip); //debugging purpose recv(fd, file_write, LINESIZE, 0); file_write[sizeof(file_write)] = '\0'; printf("3 %s\n", hacker_ip); //debugging purpose printf("%s@%s for %s\n", file_write, victim_ip, hacker_ip); //send to client send(fd, hacker_ip, 40, 0); //now is hacker_ip for debug ///////////////////////// close(fd); }//end while exit(0); } //end main Client send string: ./send -i 10.10.10.4 -f filename.ext so the script send -i (IP) and -f (FILE) at the server. Here's my output server side: 1 10.10.10.6 2 10.10.10.6 3 [email protected] for As you can see the printf(3) and the printf(ip,file,ip) fail. I don't know how and where but someone overwrite my hacker_ip string. Thanks for your help! :)

    Read the article

  • Getting timing consistency in Linux

    - by Jim Hunziker
    I can't seem to get a simple program (with lots of memory access) to achieve consistent timing in Linux. I'm using a 2.6 kernel, and the program is being run on a dual-core processor with realtime priority. I'm trying to disable cache effects by declaring the memory arrays as volatile. Below are the results and the program. What are some possible sources of the outliers? Results: Number of trials: 100 Range: 0.021732s to 0.085596s Average Time: 0.058094s Standard Deviation: 0.006944s Extreme Outliers (2 SDs away from mean): 7 Average Time, excluding extreme outliers: 0.059273s Program: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <sched.h> #include <sys/time.h> #define NUM_POINTS 5000000 #define REPS 100 unsigned long long getTimestamp() { unsigned long long usecCount; struct timeval timeVal; gettimeofday(&timeVal, 0); usecCount = timeVal.tv_sec * (unsigned long long) 1000000; usecCount += timeVal.tv_usec; return (usecCount); } double convertTimestampToSecs(unsigned long long timestamp) { return (timestamp / (double) 1000000); } int main(int argc, char* argv[]) { unsigned long long start, stop; double times[REPS]; double sum = 0; double scale, avg, newavg, median; double stddev = 0; double maxval = -1.0, minval = 1000000.0; int i, j, freq, count; int outliers = 0; struct sched_param sparam; sched_getparam(getpid(), &sparam); sparam.sched_priority = sched_get_priority_max(SCHED_FIFO); sched_setscheduler(getpid(), SCHED_FIFO, &sparam); volatile float* data; volatile float* results; data = calloc(NUM_POINTS, sizeof(float)); results = calloc(NUM_POINTS, sizeof(float)); for (i = 0; i < REPS; ++i) { start = getTimestamp(); for (j = 0; j < NUM_POINTS; ++j) { results[j] = data[j]; } stop = getTimestamp(); times[i] = convertTimestampToSecs(stop-start); } free(data); free(results); for (i = 0; i < REPS; i++) { sum += times[i]; if (times[i] > maxval) maxval = times[i]; if (times[i] < minval) minval = times[i]; } avg = sum/REPS; for (i = 0; i < REPS; i++) stddev += (times[i] - avg)*(times[i] - avg); stddev /= REPS; stddev = sqrt(stddev); for (i = 0; i < REPS; i++) { if (times[i] > avg + 2*stddev || times[i] < avg - 2*stddev) { sum -= times[i]; outliers++; } } newavg = sum/(REPS-outliers); printf("Number of trials: %d\n", REPS); printf("Range: %fs to %fs\n", minval, maxval); printf("Average Time: %fs\n", avg); printf("Standard Deviation: %fs\n", stddev); printf("Extreme Outliers (2 SDs away from mean): %d\n", outliers); printf("Average Time, excluding extreme outliers: %fs\n", newavg); return 0; }

    Read the article

  • Warning: comparison with string literals results in unspecified behaviour

    - by nunos
    So I starting the project of writing a simplified sheel for linux in c. I am not at all proficient with c nor with Linux that's exactly the reason I decided it would be a good idea. Starting with the parser, I have already encountered some problems. The code should be straightforward that's why I didn't include any comments. I am getting a warning with gcc: "comparison with string literals results in unspecified behaviour" at the lines commented with "WARNING HERE" (see code below). I have no idea why this causes an warning, but the real problem is that even though I am comparing an "<" to an "<" is doesn't get inside the if... I am looking for an answer for the problem explained, however if there's something that you see in the code that should be improved please say so. Just take in mind I am not that proficient and that this is still a work in progress (or better yet, a work in start). Thanks in advance. #include <stdio.h> #include <unistd.h> #include <string.h> typedef enum {false, true} bool; typedef struct { char **arg; char *infile; char *outfile; int background; } Command_Info; int parse_cmd(char *cmd_line, Command_Info *cmd_info) { char *arg; char *args[100]; int i = 0; arg = strtok(cmd_line, " \n"); while (arg != NULL) { args[i] = arg; arg = strtok(NULL, " \n"); i++; } int num_elems = i; cmd_info->infile = NULL; cmd_info->outfile = NULL; cmd_info->background = 0; int iarg = 0; for (i = 0; i < num_elems; i++) { if (args[i] == "&") //WARNING HERE return -1; else if (args[i] == "<") //WARNING HERE if (args[i+1] != NULL) cmd_info->infile = args[i+1]; else return -1; else if (args[i] == ">") //WARNING HERE if (args[i+1] != NULL) cmd_info->outfile = args[i+1]; else return -1; else cmd_info->arg[iarg++] = args[i]; } cmd_info->arg[iarg] = NULL; return 0; } void print_cmd(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("infile=\"%s\"\n", cmd_info->infile); printf("outfile=\"%s\"\n", cmd_info->outfile); printf("background=\"%d\"\n", cmd_info->background); } int main(int argc, char* argv[]) { char cmd_line[100]; Command_Info cmd_info; printf(">>> "); fgets(cmd_line, 100, stdin); parse_cmd(cmd_line, &cmd_info); print_cmd(&cmd_info); return 0; }

    Read the article

  • Help with simple linux shell implementation

    - by nunos
    I am implementing a simple version of a linux shell in c. I have succesfully written the parser, but I am having some trouble forking out the child process. However, I think the problem is due to arrays, pointers and such, because just started C with this project and am not still very knowledgable with them. I am getting a segmentation fault and don't know where from. Any help is greatly appreciated. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #define MAX_COMMAND_LENGTH 250 #define MAX_ARG_LENGTH 250 typedef enum {false, true} bool; typedef struct { char **arg; char *infile; char *outfile; int background; } Command_Info; int parse_cmd(char *cmd_line, Command_Info *cmd_info) { char *arg; char *args[MAX_ARG_LENGTH]; int i = 0; arg = strtok(cmd_line, " "); while (arg != NULL) { args[i] = arg; arg = strtok(NULL, " "); i++; } int num_elems = i; if (num_elems == 0) return -1; cmd_info->infile = NULL; cmd_info->outfile = NULL; cmd_info->background = 0; int iarg = 0; for (i = 0; i < num_elems-1; i++) { if (!strcmp(args[i], "<")) { if (args[i+1] != NULL) cmd_info->infile = args[++i]; else return -1; } else if (!strcmp(args[i], ">")) { if (args[i+1] != NULL) cmd_info->outfile = args[++i]; else return -1; } else cmd_info->arg[iarg++] = args[i]; } if (!strcmp(args[i], "&")) cmd_info->background = true; else cmd_info->arg[iarg++] = args[i]; cmd_info->arg[iarg] = NULL; return 0; } void print_cmd(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("infile=\"%s\"\n", cmd_info->infile); printf("outfile=\"%s\"\n", cmd_info->outfile); printf("background=\"%d\"\n", cmd_info->background); } void get_cmd(char* str) { fgets(str, MAX_COMMAND_LENGTH, stdin); str[strlen(str)-1] = '\0'; //apaga o '\n' do fim } pid_t exec_simple(Command_Info *cmd_info) { pid_t pid = fork(); if (pid < 0) { perror("Fork Error"); return -1; } if (pid == 0) { execvp(cmd_info->arg[0], cmd_info->arg); perror(cmd_info->arg[0]); exit(1); } return pid; } int main(int argc, char* argv[]) { while (true) { char cmd_line[MAX_COMMAND_LENGTH]; Command_Info cmd_info; printf(">>> "); get_cmd(cmd_line); if ( (parse_cmd(cmd_line, &cmd_info) == -1) ) return -1; parse_cmd(cmd_line, &cmd_info); if (!strcmp(cmd_info.arg[0], "exit")) exit(0); pid_t pid = exec_simple(&cmd_info); waitpid(pid, NULL, 0); } return 0; } Thanks.

    Read the article

  • Counting leaf nodes in hierarchical tree

    - by timn
    This code fills a tree with values based their depths. But when traversing the tree, I cannot manage to determine the actual number of children. node-cnt is always 0. I've already tried node-parent-cnt but that gives me lots of warnings in Valgrind. Anyway, is the tree type I've chosen even appropriate for my purpose? #include <string.h> #include <stdio.h> #include <stdlib.h> #ifndef NULL #define NULL ((void *) 0) #endif // ---- typedef struct _Tree_Node { // data ptr void *p; // number of nodes int cnt; struct _Tree_Node *nodes; // parent nodes struct _Tree_Node *parent; } Tree_Node; typedef struct { Tree_Node root; } Tree; void Tree_Init(Tree *this) { this->root.p = NULL; this->root.cnt = 0; this->root.nodes = NULL; this->root.parent = NULL; } Tree_Node* Tree_AddNode(Tree_Node *node) { if (node->cnt == 0) { node->nodes = malloc(sizeof(Tree_Node)); } else { node->nodes = realloc( node->nodes, (node->cnt + 1) * sizeof(Tree_Node) ); } Tree_Node *res = &node->nodes[node->cnt]; res->p = NULL; res->cnt = 0; res->nodes = NULL; res->parent = node; node->cnt++; return res; } // ---- void handleNode(Tree_Node *node, int depth) { int j = depth; printf("\n"); while (j--) { printf(" "); } printf("depth=%d ", depth); if (node->p == NULL) { goto out; } printf("value=%s cnt=%d", node->p, node->cnt); out: for (int i = 0; i < node->cnt; i++) { handleNode(&node->nodes[i], depth + 1); } } Tree tree; int curdepth; Tree_Node *curnode; void add(int depth, char *s) { printf("%s: depth (%d) > curdepth (%d): %d\n", s, depth, curdepth, depth > curdepth); if (depth > curdepth) { curnode = Tree_AddNode(curnode); Tree_Node *node = Tree_AddNode(curnode); node->p = malloc(strlen(s)); memcpy(node->p, s, strlen(s)); curdepth++; } else { while (curdepth - depth > 0) { if (curnode->parent == NULL) { printf("Illegal nesting\n"); return; } curnode = curnode->parent; curdepth--; } Tree_Node *node = Tree_AddNode(curnode); node->p = malloc(strlen(s)); memcpy(node->p, s, strlen(s)); } } void main(void) { Tree_Init(&tree); curnode = &tree.root; curdepth = 0; add(0, "1"); add(1, "1.1"); add(2, "1.1.1"); add(3, "1.1.1.1"); add(4, "1.1.1.1.1"); add(2, "1.1.2"); add(0, "2"); handleNode(&tree.root, 0); }

    Read the article

  • Two functions working but not when I put them together

    - by Error_404
    I'm really new to C(I have been learning Cuda and wanted to learn C so I can run everything together instead of generating data in Java/Python and copy/pasting it manually to my Cuda program to play with). I am trying to open a large file(20+gb) and parse some data but because I was having problems I decided to try to break down my problem first to verify I can open and read line by line a file and then in another file take a sample of the output of a line and try to parse it, then if all goes well I can simply bring them together. I managed(after a bit of a struggle) to get each part working but when I combine them together it doesn't work(I tried in both eclipse & QT creator. QT creator says it exited unexpectedly and eclipse just stops..). Here's the parsing part(it works exactly as I want): #include <string.h> #include <stdio.h> int main() { char line[1024] = "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 4],"; size_t len = strlen(line); memmove(line, line+1, len-3); line[len-3] = 0; printf("%s \n",line); char str[100], *s = str, *t = NULL; strcpy(str, line); while ((t = strtok(s, " ,")) != NULL) { s = NULL; printf(":%s:\n", t); } return 0; } The data in variable line is exactly as I get if I print each line of a file. But when I copy/paste it into my main program then it doesn't work(QT shows nothing and eclipse just shows the first line). This code is just a few file IO commands that are wrapped around the commands above(everything within the while loop is the exact same as above) #include <stdio.h> #include <stdlib.h> int main() { char line[1024]; FILE *fp = fopen("/Users/me/Desktop/output.txt","r"); printf("Starting.. \n"); int count = 0; int list[30]; //items will be stored here while(fgets(line, 1024, fp) != NULL){ count++; //char line[1024] = "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 4],"; size_t len = strlen(line); memmove(line, line+1, len-3); line[len-3] = 0; printf("%s \n",line); char str[100], *s = str, *t = NULL; strcpy(str, line); while ((t = strtok(s, " ,")) != NULL) { s = NULL; printf(":%s:\n", t); } } printf(" num of lines is %i \n", count); return 0; } eclipse output: Starting.. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 4 I can't figure out what I'm doing wrong. I'm using a mac with gcc 4.2, if that helps. The only thing I can think of is maybe I'm doing something wrong the way I parse the list variable so its not accessible later on(I'm not sure its a wild guess). Is there anything I'm missing?

    Read the article

  • Program using read() entering into an infinite loop

    - by Soham
    1oid ReadBinary(char *infile,HXmap* AssetMap) { int fd; size_t bytes_read, bytes_expected = 100000000*sizeof(char); char *data; if ((fd = open(infile,O_RDONLY)) < 0) err(EX_NOINPUT, "%s", infile); if ((data = malloc(bytes_expected)) == NULL) err(EX_OSERR, "data malloc"); bytes_read = read(fd, data, bytes_expected); if (bytes_read != bytes_expected) printf("Read only %d of %d bytes %d\n", \ bytes_read, bytes_expected,EX_DATAERR); /* ... operate on data ... */ printf("\n"); int i=0; int counter=0; char ch=data[0]; char message[512]; Message* newMessage; while(i!=bytes_read) { while(ch!='\n') { message[counter]=ch; i++; counter++; ch =data[i]; } message[counter]='\n'; message[counter+1]='\0'; //--------------------------------------------------- newMessage = (Message*)parser(message); MessageProcess(newMessage,AssetMap); //-------------------------------------------------- //printf("idNUM %e\n",newMessage->idNum); free(newMessage); i++; counter=0; ch =data[i]; } free(data); } Here, I have allocated 100MB of data with malloc, and passed a file big enough(not 500MB) size of 926KB about. When I pass small files, it reads and exits like a charm, but when I pass a big enough file, the program executes till some point after which it just hangs. I suspect it either entered an infinite loop, or there is memory leak. EDIT For better understanding I stripped away all unnecessary function calls, and checked what happens, when given a large file as input. I have attached the modified code void ReadBinary(char *infile,HXmap* AssetMap) { int fd; size_t bytes_read, bytes_expected = 500000000*sizeof(char); char *data; if ((fd = open(infile,O_RDONLY)) < 0) err(EX_NOINPUT, "%s", infile); if ((data = malloc(bytes_expected)) == NULL) err(EX_OSERR, "data malloc"); bytes_read = read(fd, data, bytes_expected); if (bytes_read != bytes_expected) printf("Read only %d of %d bytes %d\n", \ bytes_read, bytes_expected,EX_DATAERR); /* ... operate on data ... */ printf("\n"); int i=0; int counter=0; char ch=data[0]; char message[512]; while(i<=bytes_read) { while(ch!='\n') { message[counter]=ch; i++; counter++; ch =data[i]; } message[counter]='\n'; message[counter+1]='\0'; i++; printf("idNUM \n"); counter=0; ch =data[i]; } free(data); } What looks like is, it prints a whole lot of idNUM's and then poof segmentation fault I think this is an interesting behaviour, and to me it looks like there is some problem with memory FURTHER EDIT I changed back the i!=bytes_read it gives no segmentation fault. When I check for i<=bytes_read it blows past the limits in the innerloop.(courtesy gdb)

    Read the article

  • How to modify Perl script to move packets in diffrent directory based on version? [migrated]

    - by Peter Penzov
    I have this Perl script which is used to soft packages based on packet version: #!/usr/bin/perl -w # # Compare versions of all *.rpm files against the # latest packages installed (if installed) # # Usage: # rpmver.pl # This script looks for all *.rpm files. # use strict; use RPM2; my $rpm_db = RPM2->open_rpm_db(); for my $filename (<*.rpm>) { my $h = RPM2->open_package( $filename ); # Ensure we compare against the newest # package of the given name. my ($installed) = sort { $b <=> $a } $rpm_db->find_by_name($h->name); if (not $installed) { printf "Package %s not installed.\n", $h->as_nvre; } else { my ($result) = ($h <=> $installed); if ($result < 0) { printf "Installed package %s newer than file %s\n", $installed->as_nvre, $h->as_nvre; } else { printf "File %s newer than installed package %s\n", $h->as_nvre, $installed->as_nvre; } } } I have a Linux repository with SRPMs. I want to move the packages with the latest into different directory for example latest_lackages. How the script must be modified?

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >