Search Results

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

Page 69/74 | < Previous Page | 65 66 67 68 69 70 71 72 73 74  | Next Page >

  • GTK+ and GdkPixbuf

    - by Daniel
    Hi all, I think I've got an understanding problem of GTK. My simple application has a stream of images and I'd like to display them within my GTK Window. Up to now, it looks like this: GdkPixbuf *pb = gdk_pixbuf_new_from_data(img2, GDK_COLORSPACE_RGB, FALSE, 24/3, 320, 240, 320*3, NULL, NULL); if(pb == NULL) fprintf(stderr, "Pixbuf is null!\n"); if(image != NULL) gtk_container_remove(GTK_CONTAINER(window), image); image = gtk_image_new_from_pixbuf(pb); gtk_container_add(GTK_CONTAINER(window), image); printf("Updated!\n"); img2 is my (rgb) buffer that gets updated from a stream each time. I guess gtk_container_remove and gtk_container_add might be stupid to use for this? Here's what I've got in addition: GtkWidget *window; GtkWidget *image; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_signal_connect(GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(destroy), NULL); /* ... */ start_routine_for_stream_that_calls_the_above(...) /* ... */ gtk_widget_show_all(window); gtk_main(); My problem is that it's not working this way... either I see only the last GdkPixbuf image or I see none, which is the correct behaviour ... But how do I manage it to show an (stream of) updated GdkPixbuf? Thanks for help

    Read the article

  • Interview question: C program to sort a binary array in O(n)

    - by Zacky112
    I've comeup with the following program to do it, but it does not seem to work and goes into infinite loop. Its working is similar to quicksort. int main() { int arr[] = {1,1,0,1,0,0,0,1,0,1,0,1,0,1,0,1,0,1}; int N = 18; int *front, *last; front = arr; last = arr + N; while(front <= last) { while( (front < last) && (*front == 0) ) front++; while( (front < last) && (*last == 1) ) last--; if( front < last) { int temp = *front; *front = *last; *last = temp; front ++; last--; } } for(int i=0;i<N;i++) printf("%d ",arr[i]); return 0; }

    Read the article

  • in haskell, why do I need to specify type constraints, why can't the compiler figure them out?

    - by Steve
    Consider the function, add a b = a + b This works: *Main> add 1 2 3 However, if I add a type signature specifying that I want to add things of the same type: add :: a -> a -> a add a b = a + b I get an error: test.hs:3:10: Could not deduce (Num a) from the context () arising from a use of `+' at test.hs:3:10-14 Possible fix: add (Num a) to the context of the type signature for `add' In the expression: a + b In the definition of `add': add a b = a + b So GHC clearly can deduce that I need the Num type constraint, since it just told me: add :: Num a => a -> a -> a add a b = a + b Works. Why does GHC require me to add the type constraint? If I'm doing generic programming, why can't it just work for anything that knows how to use the + operator? In C++ template programming, you can do this easily: #include <string> #include <cstdio> using namespace std; template<typename T> T add(T a, T b) { return a + b; } int main() { printf("%d, %f, %s\n", add(1, 2), add(1.0, 3.4), add(string("foo"), string("bar")).c_str()); return 0; } The compiler figures out the types of the arguments to add and generates a version of the function for that type. There seems to be a fundamental difference in Haskell's approach, can you describe it, and discuss the trade-offs? It seems to me like it would be resolved if GHC simply filled in the type constraint for me, since it obviously decided it was needed. Still, why the type constraint at all? Why not just compile successfully as long as the function is only used in a valid context where the arguments are in Num? Thank you.

    Read the article

  • Casting/dereferencing member variable pointer from void*, is this safe?

    - by Damien
    Hi all, I had a problem while hacking a bigger project so I made a simpel test case. If I'm not omitting something, my test code works fine, but maybe it works accidentally so I wanted to show it to you and ask if there are any pitfalls in this approach. I have an OutObj which has a member variable (pointer) InObj. InObj has a member function. I send the address of this member variable object (InObj) to a callback function as void*. The type of this object never changes so inside the callback I recast to its original type and call the aFunc member function in it. In this exampel it works as expected, but in the project I'm working on it doesn't. So I might be omitting something or maybe there is a pitfall here and this works accidentally. Any comments? Thanks a lot in advance. (The problem I have in my original code is that InObj.data is garbage). #include <stdio.h> class InObj { public: int data; InObj(int argData); void aFunc() { printf("Inside aFunc! data is: %d\n", data); }; }; InObj::InObj(int argData) { data = argData; } class OutObj { public: InObj* objPtr; OutObj(int data); ~OutObj(); }; OutObj::OutObj(int data) { objPtr = new InObj(data); } OutObj::~OutObj() { delete objPtr; } void callback(void* context) { ((InObj*)context)->aFunc(); } int main () { OutObj a(42); callback((void*)a.objPtr); }

    Read the article

  • error in a c code while trying to remove whitespace

    - by mekasperasky
    this code is the base of lexer , and it does the basic operation of removing the whitespaces from a source file and rewrites it into another file with each word in separate lines . But i am not able to understand why the file lext.txt not getting updated? #include<stdio.h> /* this is a lexer which recognizes constants , variables ,symbols, identifiers , functions , comments and also header files . It stores the lexemes in 3 different files . One file contains all the headers and the comments . Another file will contain all the variables , another will contain all the symbols. */ int main() { int i; char a,b[20],c; FILE *fp1,*fp2; fp1=fopen("source.txt","r"); //the source file is opened in read only mode which will passed through the lexer fp2=fopen("lext.txt","w"); //now lets remove all the white spaces and store the rest of the words in a file if(fp1==NULL) { perror("failed to open source.txt"); //return EXIT_FAILURE; } i=0; while(!feof(fp1)) { a=fgetc(fp1); if(a!="") { b[i]=a; printf("hello"); } else { b[i]='\0'; fprintf(fp2, "%.20s\n", b); i=0; continue; } i=i+1; /*Switch(a) { case EOF :return eof; case '+':sym=sym+1; case '-':sym=sym+1; case '*':sym=sym+1; case '/':sym=sym+1; case '%':sym=sym+1; case ' */ } return 0; }

    Read the article

  • cuda 5.0 namespaces for contant memory variable usage

    - by Psypher
    In my program I want to use a structure containing constant variables and keep it on device all long as the program executes to completion. I have several header files containing the declaration of 'global' functions and their respective '.cu' files for their definitions. I kept this scheme because it helps me contain similar code in one place. e.g. all the 'device' functions required to complete 'KERNEL_1' are separated from those 'device' functions required to complete 'KERNEL_2' along with kernels definitions. I had no problems with this scheme during compilation and linking. Until I encountered constant variables. I want to use the same constant variable through all kernels and device functions but it doesn't seem to work. ########################################################################## CODE EXAMPLE ########################################################################### filename: 'common.h' -------------------------------------------------------------------------- typedef struct { double height; double weight; int age; } __CONSTANTS; __constant__ __CONSTANTS d_const; --------------------------------------------------------------------------- filename: main.cu --------------------------------------------------------------------------- #include "common.h" #include "gpukernels.h" int main(int argc, char **argv) { __CONSTANTS T; T.height = 1.79; T.weight = 73.2; T.age = 26; cudaMemcpyToSymbol(d_consts, &T, sizeof(__CONSTANTS)); test_kernel <<< 1, 16 >>>(); cudaDeviceSynchronize(); } --------------------------------------------------------------------------- filename: gpukernels.h --------------------------------------------------------------------------- __global__ void test_kernel(); --------------------------------------------------------------------------- filename: gpukernels.cu --------------------------------------------------------------------------- #include <stdio.h> #include "gpukernels.h" #include "common.h" __global__ void test_kernel() { printf("Id: %d, height: %f, weight: %f\n", threadIdx.x, d_const.height, d_const.weight); } When I execute this code, the kernel executes, displays the thread ids, but the constant values are displayed as zeros. How can I fix this?

    Read the article

  • How to implement a multi-threaded asynchronous operation?

    - by drowneath
    Here's how my current approach looks like: // Somewhere in a UI class // Called when a button called "Start" clicked MyWindow::OnStartClicked(Event &sender) { _thread = new boost::thread(boost::bind(&MyWindow::WorkToDo, this)); } MyWindow::WorkToDo() { for(int i = 1; i < 10000000; i++) { int percentage = (int)((float)i / 100000000.f); _progressBar->SetValue(percentage); _statusText->SetText("Working... %d%%", percentage); printf("Pretend to do something useful...\n"); } } // Called on every frame MyWindow::OnUpdate() { if(_thread != 0 && _thread->timed_join(boost::posix_time::seconds(0)) { _progressBar->SetValue(100); _statusText->SetText("Completed!"); delete _thread; _thread = 0; } } But I'm afraid this is far from safe since I keep getting unhandled exception at the end of the program execution. I basically want to separate a heavy task into another thread without blocking the GUI part.

    Read the article

  • The different of SHA512 between openssl and php

    - by solomon_wzs
    Here is C code: #include <openssl/sha.h> #include <stdio.h> char *hash_sha512(char *data){ SHA512_CTX ctx; char *md=malloc(sizeof(char)*(SHA512_DIGEST_LENGTH+1)); SHA512_Init(&ctx); SHA512_Update(&ctx, data, strlen(data)); SHA512_Final(md, &ctx); md[SHA512_DIGEST_LENGTH]='\0'; return md; } int main(int argc, char *argv[]){ str=hash_sha512("GFLOuJnR19881218"); printf("%s\n", str); free(str); return 1; } The output: ?<?4????IIA[r?? ?#? 6p?8jD????J?b9?????^X? Here is PHP code: $hash=hash('sha512', 'GFLOuJnR19881218', TRUE); The output: ?<??4??j??II?-A[r???? ??#??D6p?8jD???????J?b9?????^X? The results of C code and PHP code are different, what is wrong with my code?

    Read the article

  • Declaring two large 2d arrays gives segmentation fault.

    - by pfdevil
    Hello, i'm trying to declare and allocate memory for two 2d-arrays. However when trying to assign values to itemFeatureQ[39][16816] I get a segmentation vault. I can't understand it since I have 2GB of RAM and only using 19MB on the heap. Here is the code; double** reserveMemory(int rows, int columns) { double **array; int i; array = (double**) malloc(rows * sizeof(double *)); if(array == NULL) { fprintf(stderr, "out of memory\n"); return NULL; } for(i = 0; i < rows; i++) { array[i] = (double*) malloc(columns * sizeof(double *)); if(array == NULL) { fprintf(stderr, "out of memory\n"); return NULL; } } return array; } void populateUserFeatureP(double **userFeatureP) { int x,y; for(x = 0; x < CUSTOMERS; x++) { for(y = 0; y < FEATURES; y++) { userFeatureP[x][y] = 0; } } } void populateItemFeatureQ(double **itemFeatureQ) { int x,y; for(x = 0; x < FEATURES; x++) { for(y = 0; y < MOVIES; y++) { printf("(%d,%d)\n", x, y); itemFeatureQ[x][y] = 0; } } } int main(int argc, char *argv[]){ double **userFeatureP = reserveMemory(480189, 40); double **itemFeatureQ = reserveMemory(40, 17770); populateItemFeatureQ(itemFeatureQ); populateUserFeatureP(userFeatureP); return 0; }

    Read the article

  • CArray doesn't call copy constructors on memory reallocations, now what?

    - by MMx
    Suppose I have a class that requires copy constructor to be called to make a correct copy of: struct CWeird { CWeird() { number = 47; target = &number; } CWeird(const CWeird &other) : number(other.number), target(&number) { } void output() { printf("%d %d\n", *target, number); } int *target, number; }; Now the trouble is that CArray doesn't call copy constructors on its elements when reallocating memory (only memcpy from the old memory to the new), e.g. this code CArray<CWeird> a; a.SetSize(1); a[0].output(); a.SetSize(2); a[0].output(); results in 47 47 -572662307 47 I don't get this. Why is it that std::vector can copy the same objects properly and CArray can't? What's the lesson here? Should I use only classes that don't require explicit copy constructors? Or is it a bad idea to use CArray for anything serious?

    Read the article

  • c Pointer to pointer, or passing list to functions

    - by user361808
    Hi, I am new to c programming. Could anyone please tell me what's wrong with the following program? typedef struct Person_s { int age; char name[40]; } Person_t; int process_list(int *countReturned, Person_t **p_list) { Person_t *rowPtr=0; //the actual program will fethc data from DB int count =1; if(!((*p_list) = (Person_t *) malloc(sizeof(Person_t)))) { return -1; } rowPtr = *p_list; rowPtr[count-1].age =19; strcpy(rowPtr[count-1].name,"Prince Dastan"); *countReturned = count; return 0; } int main(int argc, char *argv[]) { Person_t *tmpPerson=0; Person_t **p_list=0; int *count=0; int i; process_list(count,p_list); tmpPerson = *p_list; for(i=0; i< *count; i++) { printf("Name: %s , age: %d\n",tmpPerson->name,tmpPerson->age); tmpPerson++; } //free(tmpPerson); return 0; }

    Read the article

  • compile c problem in emacs (ubuntu)

    - by user565739
    I wrote a very simple program like: ( sorry, I typed the code in the right way, but the display is wired. How could I fix it?) #include <stdio.h> int main( void ) { int i; for ( i = 0; i <= 10; i++ ) { printf( "%d hello!\n", i); } return 0; } Usually, I compile c program in terminal with the command cc -o xxx xxx.c So in Emacs, when I type M-x compile, I change make -k to cc -o. But I got error like cc: argument to '-o' is missing What's the problem? If I use make, then I still got error No targets specified and no makefiles found. Finally, if the above problem is fixed, how could I define a custom hotkey for compile? I have already know how to do something like global-set-key [f8] 'goto-line But I don't know to set a hotkey for an action only for c-mode.

    Read the article

  • segmentation fault when using pointer to pointer

    - by user3697730
    I had been trying to use a pointer to pointer in a function,but is seems that I am not doing the memory allocation correctly... My code is: #include<stdio.h> #include<math.h> #include<ctype.h> #include<stdlib.h> #include<string.h> struct list{ int data; struct list *next; }; void abc (struct list **l,struct list **l2) { *l2=NULL; l2=(struct list**)malloc( sizeof(struct list*)); (*l)->data=12; printf("%d",(*l)->data); (*l2)->next=*l2; } int main() { struct list *l,*l2; abc(&l,&l2); system("pause"); return(0); } This code compiles,but I cannot run thw program..I get a segmentation fault..What should I do?Any help would be appreciated!

    Read the article

  • Beginner Question ; About Prime Generation in "C" - What is wrong with my code ? -

    - by alorsoncode
    I'm a third year irregular CS student and ,i just realized that i have to start coding. I passed my coding classes with lower bound grades so that i haven't a good background in coding&programming. I'm trying to write a code that generates prime numbers between given upper and lower bounds. Not knowing C well, enforce me to write a rough code then go over it to solve. I can easily set up the logic for intended function but i probably create a wrong algorithm through several different ways. Here I share my last code, i intend to calculate that when a number gives remainder Zero , it should be it self and 1 , so that count==2; What is wrong with my implementation and with my solution generating style? I hope you will warm me up to programming world, i couldn't find enough motivation and courage to get deep into programming. Thanks in Advance :) Stdio and Math.h is Included int primegen(int down,int up) { int divisor,candidate,count=0,k; for(candidate=down;candidate<=up;candidate++) { for(divisor=1;divisor<=candidate;divisor++) { k=(candidate%divisor); } if (k==0) count++; if(count==2) { printf("%d\n", candidate); count=0; } else { continue; } } } int main() { primegen(3,15); return 0; }

    Read the article

  • [C]Dynamic allocation memory of structure, related to GTK

    - by MakeItWork
    Hello, I have following structure: typedef struct { GtkWidget* PoziomaLinijka; GtkWidget* PionowaLinijka; GtkWidget* Label1; GtkWidget* Label2; gint x,y; } StrukturaDrawing; And i need to allocate it on the heap because later I have functions which uses that structure and I don't want to use global variables. So I allocate it like this: StrukturaDrawing* Wsk; Wsk = (StrukturaDrawing*)malloc(sizeof(StrukturaDrawing)); if (!Wsk) { printf("Error\n"); } And it doesn't returning error and also works great with other functions, it works the way I wanted it to work so finally i wanted to free that memory and here is problem because in Debug Mode compilator bitches: First-chance exception at 0x102d12b4 in GTK.exe: 0xC0000005: Access violation reading location 0xfffffffc. Unhandled exception at 0x102d12b4 in GTK.exe: 0xC0000005: Access violation reading location 0xfffffffc. I connect callback to my function, like that: g_signal_connect(G_OBJECT(Okno), "destroy", G_CALLBACK(Wyjscie), Wsk); Function which is suppose to free memory and close program: void Wyjscie(GtkWindow* window, GdkEvent* event, StrukturaDrawing* data) { gtk_main_quit(); free(data); data = NULL; } Any help really appreciated.

    Read the article

  • Parameter error with Mysqli

    - by Morgan Green
    When I run this Query I recieve Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /home/morgan58/public_html/wow/includes/index/index_admin.php on line 188 SELECT * FROM characters WHERE id=5 Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, boolean given in /home/morgan58/public_html/wow/includes/index/index_admin.php on line 194 The Query is running and it is strying to select the correct information, but for on the actual output it's giving me a fetch_array error; if anyone can see where the error lies it'd be much appreciated. Thank you. <?php $adminid= $admin->get_id(); $characterdb= 'characters'; $link = mysqli_connect("$server", "$user", "$pass", "$characterdb"); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT * FROM characters WHERE id=$adminid"; $result = mysqli_query($link, $query); while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { echo $query; echo $row['name']; } mysqli_free_result($result); mysqli_close($link); ?>

    Read the article

  • What's the meaning of 'char (*p)[5];'?

    - by jpmelos
    people. I'm trying to grasp the differences between these three declarations: char p[5]; char *p[5]; char (*p)[5]; I'm trying to find this out by doing some tests, because every guide of reading declarations and stuff like that has not helped me so far. I wrote this little program and it's not working (I've tried other kinds of use of the third declaration and I've ran out of options): #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { char p1[5]; char *p2[5]; char (*p3)[5]; strcpy(p1, "dead"); p2[0] = (char *) malloc(5 * sizeof(char)); strcpy(p2[0], "beef"); p3[0] = (char *) malloc(5 * sizeof(char)); strcpy(p3[0], "char"); printf("p1 = %s\np2[0] = %s\np3[0] = %s\n", p1, p2[0], p3[0]); return 0; } The first and second works alright, and I've understood what they do. What is the meaning of the third declaration and the correct way to use it? Thank you!

    Read the article

  • fgets throwing unhandled exception while parsing stl

    - by user3478400
    I am new to c++, I am trying to parse a stl file which is of about 64MB and has about ~18K lines in it. The code works fine for first few 100 lines but then fgets throws following exception: "Unhandled exception at 0x77B0BAC5 (ntdll.dll) in STLparser.exe: 0xC0000024: There is a mismatch between the type of object required by the requested operation and the type of object that is specified in the request." I have checked manually the line for which fgets throws exception, there is nothing out of ordinary there. I am out of options for now. Any help to fix this issue will be greatly appreciated. ================CODE========================== #include<fstream> #include<iostream> #include"ParseString.h" #include"Vectors.h" using namespace std; int main(void) { //Define variables FILE *file; char *line = new char; parsestring oneline; int n_Vols = 0, n_Elms = 0, n_nods = -1, E = 0; Nod *nodes = new Nod(); Nod dummy; Elm *elements = new Elm(); int mycounter = 0; //Open file fopen_s(&file, "sample.stl", "r"); while (fgets(line, 1024, file) != NULL) //**********Getting Error Here************* { // populate required data } fclose(file); printf("%d,%d,%d", n_Vols, n_Elms, n_nods); getchar(); return 0; } ===================When broken, execution resumes at this function (not my function, something internal) void __cdecl _unlock ( int locknum ) { /* * leave the critical section. */ LeaveCriticalSection( _locktable[locknum].lock ); }

    Read the article

  • free( ) pointers

    - by user1043625
    I'm required to use a special library to keep track of my memory leaks where malloc()= allocate( ) and free( ) = unallocate( ). I'm trying to complete free a linked-list but it seems like the "root" value isn't being freed. typedef struct _node { struct _node *child; char *command; } Command_list; void delete_commands(Command_list **root) { Command_list *temp; while( *root != NULL ){ temp = (*root)->child; //printf("STRING: %s\n", *root->command ); unallocate( *root ); *root = temp; } } The function that's calling it void file_processing( .... ){ Command_list *root = allocate(sizeof (Command_list)); root = NULL; .... delete_commands( &root ); } } I believe that Command_list *root = allocate(sizeof (Command_list)) isn't being properly de-allocated for some reason. Anyone can give me some hints? UPDATE: I found out that instead of Command_list *root = allocate(sizeof (Command_list)); root = NULL; this works: Command_list *root = NULL;

    Read the article

  • Misaligned Pointer Performance

    - by Elite Mx
    Aren't misaligned pointers (in the BEST possible case) supposed to slow down performance and in the worst case crash your program (assuming the compiler was nice enough to compile your invalid c program). Well, the following code doesn't seem to have any performance differences between the aligned and misaligned versions. Why is that? /* brutality.c */ #ifdef BRUTALITY xs = (unsigned long *) ((unsigned char *) xs + 1); #endif ... /* main.c */ #include <stdio.h> #include <stdlib.h> #define size_t_max ((size_t)-1) #define max_count(var) (size_t_max / (sizeof var)) int main(int argc, char *argv[]) { unsigned long sum, *xs, *itr, *xs_end; size_t element_count = max_count(*xs) >> 4; xs = malloc(element_count * (sizeof *xs)); if(!xs) exit(1); xs_end = xs + element_count - 1; sum = 0; for(itr = xs; itr < xs_end; itr++) *itr = 0; #include "brutality.c" itr = xs; while(itr < xs_end) sum += *itr++; printf("%lu\n", sum); /* we could free the malloc-ed memory here */ /* but we are almost done */ exit(0); } Compiled and tested on two separate machines using gcc -pedantic -Wall -O0 -std=c99 main.c for i in {0..9}; do time ./a.out; done

    Read the article

  • problem using fprintf

    - by shiran bar
    I'm trying to print to a text file numerous variables yet it doesn't work. I checked and verified that i write it in the correct syntax. I also checked the return value and it's positive therefore i know it did write to the file, however when i open the file it's empty. I would be happy for some help. This is the code: I initiate DynsaleDayPtr in the main: FILE* DynsaleDayPtr = CreateTextFiles("sale_day.txt"); Create function: FILE* CreateTextFiles (char* fileName) { FILE* saleFilePtr=NULL; if((saleFilePtr=fopen(fileName,"a+"))==NULL) printf("File couldn't be opened\n"); return saleFilePtr; } The call to the function TextAddSale is done from a function that is called in the main: TextAddSale(DynSaleDayPtr,dynNumOfRecords); Bool TextAddSale (FILE* DynsaleDayPtr, int* dynNumOfRecords) { char id[6]; char name [50]; char priceChar[20]; char* tmp = NULL; int price=-1; DynamicRecord * newRec=NULL; scanf("%s%s%s",id,name,priceChar); newRec = (DynamicRecord *)malloc(sizeof(DynamicRecord)); if (newRec == NULL) return False; tmp = (char*)malloc(strlen(name)+1); if (tmp == NULL) { free (newRec); return False; } strcpy(tmp,name); newRec->productName = tmp; strcpy(newRec->productId, id); newRec->productPrice=atoi (priceChar); if (fprintf(DynsaleDayPtr,"%d %s %s %d", strlen(newRec->productName), newRec->productId, newRec->productName, newRec->productPrice)>0) { *dynNumOfRecords=(*dynNumOfRecords)+1; return True; } } thanks!

    Read the article

  • Parsing string based on initial format

    - by Kayla
    I'm trying to parse a set of lines and extract certain parts of the string based on an initial format (reading a configuration file). A little more explanation: the format can contain up to 4 parts to be formatted. This case, %S will skip the part, %a-%c will extract the part and will be treated as a string, %d as int. What I am trying to do now is to come up with some clever way to parse it. So far I came up with the following prototype. However, my pointer arithmetic still needs some work to skip/extract the parts. Ultimately each part will be stored on an array of structs. Such as: struct st_temp { char *parta; char *partb; char *partc; char *partd; }; ... #include <stdio.h> #include <string.h> #define DIM(x) (sizeof(x)/sizeof(*(x))) void process (const char *fmt, const char *line) { char c; const char *src = fmt; while ((c = *src++) != '\0') { if (c == 'S'); // skip part else if (c == 'a'); // extract %a else if (c == 'b'); // extract %b else if (c == 'c'); // extract %c else if (c == 'd'); // extract %d (int) else { printf("Unknown format\n"); exit(1); } } } static const char *input[] = { "bar 200.1 / / (zaz) - \"bon 10\"", "foo 100.1 / / (baz) - \"apt 20\"", }; int main (void) { const char *fmt = "%S %a / / (%b) - \"%c %d\""; size_t i; for(i = 0; i < DIM (input); i++) { process (fmt, input[i]); } return (0); }

    Read the article

  • array and point problem

    - by bezetek
    Here, I have a bad program. Its outputs confusing me, anyone can tell me why ? #include <stdio.h> #include <stdlib.h> int main() { int i = 0; char *a_result[10]; char *b_result[10]; for (i = 0; i < 10; i++) { char a_array[10]; char *b_array = malloc(10*sizeof(char)); int j = 0; for (j = 0; j < 9; j++) { a_array[j] = 'a' + i; b_array[j] = 'a' + i; } a_array[j] = '\0'; b_array[j] = '\0'; a_result[i] = a_array; b_result[i] = b_array; } for (i = 0; i < 10; i++) printf("a_result: %s b_result: %s\n",a_result[i],b_result[i]); return 0; } I think the a_result and b_result should be the same, but it is not. Here is the output on my computer. a_result: jjjjjjjjj b_result: aaaaaaaaa a_result: jjjjjjjjj b_result: bbbbbbbbb a_result: jjjjjjjjj b_result: ccccccccc a_result: jjjjjjjjj b_result: ddddddddd a_result: jjjjjjjjj b_result: eeeeeeeee a_result: jjjjjjjjj b_result: fffffffff a_result: jjjjjjjjj b_result: ggggggggg a_result: jjjjjjjjj b_result: hhhhhhhhh a_result: jjjjjjjjj b_result: iiiiiiiii a_result: jjjjjjjjj b_result: jjjjjjjjj any explanation about this is appreciate!

    Read the article

  • make it simpler and efficient

    - by gcc
    temp1=*tutar[1]; //i hold input in char *tutar[] if(temp1!='x'||temp1!='n') arrays[1]=malloc(sizeof(int)*num_arrays); //if second input is int a=0; n=i; for(i=1;i<n;++i) { temp1=*tutar[i]; if(temp1=='d') { ++i; j=atoi(tutar[i]); free(arrays[j]); continue; } if(temp1=='x') break; if(temp1=='n')//if it is n { a=0; ++j; arrays[j]=malloc(sizeof(int)*num_arrays);//create and allocate continue; } ++a; if(a>num_arrays) //resize the array arrays[j]=realloc(arrays[j],sizeof(int)*(num_arrays+a)); *(arrays[j]+a-1)=atoi(tutar[i]); printf("%d",arrays[1][1]); } arrays is pointer when you see x exit you see n create (old one is new array[a] new one is array[i+1]) you see d delete arrays[i] according to int after d first number is size of max arrays and where is the error in code input is composed from int and n d x i make a program -taking input(first input must be int) -according to input(there is comman in input like n or d or j , i fill array with number and use memory efficiently -j is jumb to array[x] ( x is int coming after j in input)

    Read the article

  • Program that edits string and prints each word individually with C

    - by Michael_19
    I keep getting the error segmentation fault (core dumped) when I run my progam. #include<stdio.h> #include<stdlib.h> int nextword(char *str); int main(void) { char str[] = "Hello! Today is a beautiful day!!\t\n"; int i = nextword(str); while(i != -1) { printf("%s\n",&(str[i])); i = nextword(NULL); } return 0; } int nextword(char *str) { // create two static variables - these stay around across calls static char *s; static int nextindex; int thisindex; // reset the static variables if (str != NULL) { s = str; thisindex = 0; // TODO: advance this index past any leading spaces while (s[thisindex]=='\n' || s[thisindex]=='\t' || s[thisindex]==' ' ) thisindex++; } else { // set the return value to be the nextindex thisindex = nextindex; } // if we aren't done with the string... if (thisindex != -1) { nextindex = thisindex; // TODO: two things // 1: place a '\0' after the current word // 2: advance nextindex to the beginning // of the next word while (s[nextindex] != ' ' && s[nextindex] != '\0') nextindex++; str[nextindex] = '\0'; nextindex++; } return thisindex; } The goal of the program is to print each word in the string str[] to the console on a new line. I am a beginning programmer and this is an assignment so I must use this type of format (no string library allowed). I just would like to know where I went wrong and how I can fix it.

    Read the article

< Previous Page | 65 66 67 68 69 70 71 72 73 74  | Next Page >