Search Results

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

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

  • calculating min and max of 2-D array in c

    - by m2010
    This program to calculate sum,min and max of array elements Max value is the problem, it is always not true. void main(void) { int degree[3][2]; int min_max[][]; int Max=min_max[0][0]; int Min=min_max[0][0]; int i,j; int sum=0; clrscr(); for(i=0;i<3;i++) { for(j=0;j<2;j++) { printf("\n enter degree of student no. %d in subject %d:",i+1,j+1); scanf("%d",&degree[i][j]); } } for(i=0;i<3;i++) { for(j=0;j<2;j++) { printf("\n Student no. %d degree in subject no. %d is %d",i+1,j+1,degree[i][j]); } } for(i=0;i<3;i++) { sum=0; for(j=0;j<2;j++) { sum+=degree[i][j]; } printf("\n sum of degrees of student no. %d is %d",i+1,sum); min_max[i][j]=sum; if(min_max[i][j] <Min) { Min=min_max[i][j]; } else if(min_max[i][j]>Max) { Max=min_max[i][j]; } } printf("\nThe minimum sum of degrees of student no. %d is %d",i,Min); printf("\nThe maximum sum of degrees of student no. %d is %d",i,Max); getch(); }

    Read the article

  • Loading machinecode from file into memory and executing in C -- mprotect failing

    - by chartreusekitsune
    Hi I'm trying to load raw machine code into memory and run it from within a C program, right now when the program executes it breaks when trying to run mprotect on the memory to make it executable. I'm also not entirely sure that if the memory does get set right it will execute. What I currently have is the following: #include <memory.h> #include <sys/mman.h> #include <stdio.h> int main ( int argc, char **argv ) { FILE *fp; int sz = 0; char *membuf; int output = 0; fp = fopen(argv[1],"rb"); if(fp == NULL) { printf("Failed to open file, aborting!\n"); exit(1); } fseek(fp, 0L, SEEK_END); sz = ftell(fp); fseek(fp, 0L, SEEK_SET); membuf = (char *)malloc(sz*sizeof(char)); if(membuf == NULL) { printf("Failed to allocate memory, aborting!\n"); exit(1); } memset(membuf, 0x90, sz*sizeof(char)); if( mprotect(membuf, sz*sizeof(char), PROT_EXEC | PROT_READ | PROT_WRITE) == -1) { printf("mprotect failed!!! aborting!\n"); exit(1); } if((sz*sizeof(char)) != fread(membuf, sz*sizeof(char), 1, fp)) { printf("Read failed, aborting!\n"); exit(1); } __asm__ ( "call %%eax;" : "=a" (output) : "a" (membuf) ); printf("Output = %x\n", output); return 0; }

    Read the article

  • aio_read from file error on OS X

    - by Pyetras
    The following code: #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <aio.h> #include <errno.h> int main (int argc, char const *argv[]) { char name[] = "abc"; int fdes; if ((fdes = open(name, O_RDWR | O_CREAT, 0600 )) < 0) printf("%d, create file", errno); int buffer[] = {0, 1, 2, 3, 4, 5}; if (write(fdes, &buffer, sizeof(buffer)) == 0){ printf("writerr\n"); } struct aiocb aio; int n = 2; while (n--){ aio.aio_reqprio = 0; aio.aio_fildes = fdes; aio.aio_offset = sizeof(int); aio.aio_sigevent.sigev_notify = SIGEV_NONE; int buffer2; aio.aio_buf = &buffer2; aio.aio_nbytes = sizeof(buffer2); if (aio_read(&aio) != 0){ printf("%d, readerr\n", errno); }else{ const struct aiocb *aio_l[] = {&aio}; if (aio_suspend(aio_l, 1, 0) != 0){ printf("%d, suspenderr\n", errno); }else{ printf("%d\n", *(int *)aio.aio_buf); } } } return 0; } Works fine on Linux (Ubuntu 9.10, compiled with -lrt), printing 1 1 But fails on OS X (10.6.6 and 10.6.5, I've tested it on two machines): 1 35, readerr Is this possible that this is due to some library error on OS X, or am I doing something wrong?

    Read the article

  • pointer-to-pointer of derived class in multiple inheritance

    - by Abdul jalil
    i have 3 classes A,B and C. C is derived from A and B. i get pointer to pointer of class C and cast to A** , and B ** , the variable that hold the the B** has the address of A** in my example B ** BdoublePtr hold the address of A** .i am using the following code #include "conio.h" #include "stdio.h" #include "string.h" class A{ public: A() { strA=new char[30]; strcpy(strA,"class A"); } char *strA; }; class B { public: B() { strB=new char[30]; strcpy(strB,"class B"); } char *strB; }; class C :public A, public B { public: C() { strC=new char[30]; strcpy(strC,"class C"); } char *strC; }; int main(void) { C* ptrC=new C(); A * Aptr=(A*)ptrC; printf("\n class A value : %s",Aptr-strA); B * Bptr=(B*)ptrC; printf("\n class B value :%s",Bptr-strB); printf("\n\nnow with double pointer "); A ** AdoublePtr=(A **)&ptrC; Aptr=AdoublePtr; printf("\n class A value : %s",Aptr-strA); B * BdoublePtr=(B **)&ptrC; Bptr=*BdoublePtr; printf("\n class B value : %s",Bptr-strB); getch(); return 0; }

    Read the article

  • C Language: Why I cannot transfer file from server to client?

    - by user275753
    I want to ask, why I cannot transfer file from server to client? When I start to send the file from server, the client side program will have problem. So, I spend some times to check the code, But I still cannot find out the problem Can anyone point out the problem for me? thanks a lot! [client side code] include include include include include include include define SA struct sockaddr define S_PORT 5678 define MAXLEN 1000 define true 1 void errexit(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); WSACleanup(); exit(1); } int main(int argc, char *argv []) { WSADATA wsadata; SOCKET sockfd; int number,message; char outbuff[MAXLEN],inbuff[MAXLEN]; char PWD_buffer[_MAX_PATH]; struct sockaddr_in servaddr; FILE *fp; int numbytes; char buf[2048]; if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) errexit("WSAStartup failed\n"); if (argc != 2) errexit("client IPaddress"); if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET ) errexit("socket error: error number %d\n", WSAGetLastError()); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(S_PORT); if ( (servaddr.sin_addr.s_addr = inet_addr(argv[1])) == INADDR_NONE) errexit("inet_addr error: error number %d\n", WSAGetLastError()); if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR) errexit("connect error: error number %d\n", WSAGetLastError()); if ( (fp = fopen("C:\\users\\pc\\desktop\\COPY.c", "wb")) == NULL){ perror("fopen"); exit(1); } printf("Still NO PROBLEM!\n"); //Receive file from server while(1){ numbytes = read(sockfd, buf, sizeof(buf)); printf("read %d bytes, ", numbytes); if(numbytes == 0){ printf("\n"); break; } numbytes = fwrite(buf, sizeof(char), numbytes, fp); printf("fwrite %d bytes\n", numbytes); } fclose(fp); close(sockfd); return 0; } server side code include include include include include include include include define SA struct sockaddr define S_PORT 5678 define MAXLEN 1000 void errexit(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); WSACleanup(); exit(1); } int main(int argc, char *argv []) { WSADATA wsadata; SOCKET listenfd, connfd; int number, message, numbytes; int h, i, j, alen; int nread; struct sockaddr_in servaddr, cliaddr; FILE *in_file, *out_file, *fp; char buf[4096]; if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) errexit("WSAStartup failed\n"); listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd == INVALID_SOCKET) errexit("cannot create socket: error number %d\n", WSAGetLastError()); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(S_PORT); if (bind(listenfd, (SA *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR) errexit("can't bind to port %d: error number %d\n", S_PORT, WSAGetLastError()); if (listen(listenfd, 5) == SOCKET_ERROR) errexit("can't listen on port %d: error number %d\n", S_PORT, WSAGetLastError()); alen = sizeof(SA); connfd = accept(listenfd, (SA *) &cliaddr, &alen); if (connfd == INVALID_SOCKET) errexit("accept failed: error number %d\n", WSAGetLastError()); printf("accept one client from %s!\n", inet_ntoa(cliaddr.sin_addr)); fp = fopen ("client.c", "rb"); // open file stored in server if (fp == NULL) { printf("\nfile NOT exist"); } //Sending file while(!feof(fp)){ numbytes = fread(buf, sizeof(char), sizeof(buf), fp); printf("fread %d bytes, ", numbytes); numbytes = write(connfd, buf, numbytes); printf("Sending %d bytes\n",numbytes); } fclose (fp); closesocket(listenfd); closesocket(connfd); return 0; }

    Read the article

  • C Programming: malloc() for a 2D array (using pointer-to-pointer)

    - by vikramtheone
    Hi Guys, yesterday I had posted a question: How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function? From the answers I got, I was able to understand what mistake I was doing. I'm facing a new problem now, can anyone help out with this? I want to dynamically allocate a 2D array, so I'm passing a Pointer-to-Pointer from my main() to another function called alloc_2D_pixels(...), where I use malloc(...) and for(...) loop to allocate memory for the 2D array. Well, after returning from the alloc_2D_pixels(...) function, the pointer-to-pointer still remains NULL, so naturally, when I try accessing or try to free(...) the Pointer-to-Pointer, the program hangs. Can anyone suggest me what mistakes I'm doing here? Help!!! Vikram SOURCE: main() { unsigned char **ptr; unsigned int rows, cols; if(alloc_2D_pixels(&ptr, rows, cols)==ERROR) // Satisfies this condition printf("Memory for the 2D array not allocated"); // NO ERROR is returned if(ptr == NULL) // ptr is NULL so no memory was allocated printf("Yes its NULL!"); // Because ptr is NULL, with any of these 3 statements below the program HANGS ptr[0][0] = 10; printf("Element: %d",ptr[0][0]); free_2D_alloc(&ptr); } signed char alloc_2D_pixels(unsigned char ***memory, unsigned int rows, unsigned int cols) { signed char status = NO_ERROR; memory = malloc(rows * sizeof(unsigned char** )); if(memory == NULL) { status = ERROR; printf("ERROR: Memory allocation failed!"); } else { int i; for(i = 0; i< cols; i++) { memory[i] = malloc(cols * sizeof(unsigned char)); if(memory[i]==NULL) { status = ERROR; printf("ERROR: Memory allocation failed!"); } } } // Inserted the statements below for debug purpose only memory[0][0] = (unsigned char)10; // I'm able to access the array from printf("\nElement %d",memory[0][0]); // here with no problems return status; } void free_2D_pixels(unsigned char ***ptr, unsigned int rows) { int i; for(i = 0; i < rows; i++) { free(ptr[i]); } free(ptr); }

    Read the article

  • Unintentional concatenation in Bison/Yacc grammar.

    - by troutwine
    I am experimenting with lex and yacc and have run into a strange issue, but I think it would be best to show you my code before detailing the issue. This is my lexer: %{ #include <stdlib.h> #include <string.h> #include "y.tab.h" void yyerror(char *); %} %% [a-zA-Z]+ { yylval.strV = yytext; return ID; } [0-9]+ { yylval.intV = atoi(yytext); return INTEGER; } [\n] { return *yytext; } [ \t] ; . yyerror("invalid character"); %% int yywrap(void) { return 1; } This is my parser: %{ #include <stdio.h> int yydebug=1; void prompt(); void yyerror(char *); int yylex(void); %} %union { int intV; char *strV; } %token INTEGER ID %% program: program statement EOF { prompt(); } | program EOF { prompt(); } | { prompt(); } ; args: /* empty */ | args ID { printf(":%s ", $<strV>2); } ; statement: ID args { printf("%s", $<strV>1); } | INTEGER { printf("%d", $<intV>1); } ; EOF: '\n' %% void yyerror(char *s) { fprintf(stderr, "%s\n", s); } void prompt() { printf("> "); } int main(void) { yyparse(); return 0; } A very simple language, consisting of no more than strings and integer and a basic REPL. Now, you'll note in the parser that args are output with a leading colon, the intention being that, when combined with the first pattern of the rule of the statement the interaction with the REPL would look something like this: > aaa aa a :aa :a aaa> However, the interaction is this: > aaa aa a :aa :a aaa aa aa > Why does the token ID in the following rule statement: ID args { printf("%s", $<strV>1); } | INTEGER { printf("%d", $<intV>1); } ; have the semantic value of the total input string, newline included? How can my grammar be reworked so that the interaction I intended?

    Read the article

  • the problem about different treatment to __VA_ARGS__ when using VS 2008 and GCC

    - by liuliu
    I am trying to identify a problem because of an unusual usage of variadic macros. Here is the hypothetic macro: #define va(c, d, ...) c(d, __VA_ARGS__) #define var(a, b, ...) va(__VA_ARGS__, a, b) var(2, 3, printf, “%d %d %d\n”, 1); For gcc, the preprocessor will output printf("%d %d %d\n", 1, 2, 3) but for VS 2008, the output is printf, “%d %d %d\n”, 1(2, 3); I suspect the difference is caused by the different treatment to VA_ARGS, for gcc, it will first expand the expression to va(printf, "%d %d %d\n", 1, 2, 3), and treat 1, 2, 3 as the VA_ARGS for macro va. But for VS 2008, it will first treat b as VA_ARGS for macro va, and then do the expansion. Which one is correct interpretation for C99 variadic macro? or my usage falls into an undefined behavior?

    Read the article

  • What's wrong in this C program..? [closed]

    - by AGeek
    struct bucket { int nStrings; //No. of Strings in a Bucket. char strings[MAXSTRINGS][MAXWORDLENGTH]; // A bucket row can contain maximum 9 strings of max string length 10. };//buck[TOTBUCKETS]; void lexSorting(char array[][10], int lenArray, int symb) //symb - symbol, sorting based on character symbols. { int i, j; int bucketNo; int tBuckNStrings; bucket buck[TOTBUCKETS]; for(i=0; i<lenArray; i++) { bucketNo = array[i][symb] - 'a'; // Find Bucket No. in which the string is to be placed. tBuckNStrings = buck[bucketNo].nStrings; // temp variable for storing nStrings var in bucket structure. strcpy(buck[bucketNo].strings[tBuckNStrings],array[i]); // Store the string in its bucket. buck[bucketNo].nStrings = ++tBuckNStrings; //Increment the nStrings value of the bucket. } // lexSorting(array, lenArray, ++symb); printf("****** %d ******\n", symb); for(i=0; i<TOTBUCKETS; i++) { printf("%c = ", i+'a'); for(j=0; j<buck[i].nStrings; j++) printf("%s ",buck[i].strings[j]); printf("\n"); } } int main() { char array[][10] = {"able","aback","a","abet","acid","yawn","yard","yarn","year","yoke"}; int lenArray = 10; int i; printf("Strings: "); for(i=0; i<lenArray; i++) printf("%s ",array[i]); printf("\n"); lexSorting(array, lenArray, 0); } Well here is the complete code, that I am trying. since its been a long time since i have touched upon C programming, so somewhere i am making mistake in structure declaration. The problem goes here:- 1) I have declared a structure above and its object as array(buck[]). 2) Now when I declare this object array along with the structure, it works fine.. I have commented this thing right now. 3) But when I declare this object array inside the function.. because ultimately i have to declare inside function( as i need to build a recursive program, where objects will be created in very recursive call) then the program is throwing segmentation fault. Expected Output > [others@centos htdocs]$ ./a.out > Strings: able aback a abet acid yawn > yard yarn year yoke > ****** 0 ****** > a = able aback a abet acid > b = > c > . > . > y = yawn yard yarnyear yoke > z = Actual Output [others@centos htdocs]$ ./a.out Strings: able aback a abet acid yawn yard yarn year yoke Segmentation fault I have no idea, what difference I made in this. Kindly help. Thanks.

    Read the article

  • Quick question regarding this issue, Why doesnt it print out the second value(converted second value

    - by sil3nt
    Quick question, What have I done wrong here. The purpose of this code is to get the input into a string, the input being "12 34", with a space in between the "12" and "32" and to convert and print the two separate numbers from an integer variable known as number. Why doesn't the second call to the function copyTemp, not produce the value 34?. I have an index_counter variable which keeps track of the string index and its meant to skip the 'space' character?? what have i done wrong? thanks. #include <stdio.h> #include <string.h> int index_counter = 0; int number; void copyTemp(char *expr,char *temp); int main(){ char exprstn[80]; //as global? char tempstr[80]; gets(exprstn); copyTemp(exprstn,tempstr); printf("Expression: %s\n",exprstn); printf("Temporary: %s\n",tempstr); printf("number is: %d\n",number); copyTemp(exprstn,tempstr); //second call produces same output shouldnt it now produce 34 in the variable number? printf("Expression: %s\n",exprstn); printf("Temporary: %s\n",tempstr); printf("number is: %d\n",number); return 0; } void copyTemp(char *expr,char *temp){ int i; for(i = index_counter; expr[i] != '\0'; i++){ if (expr[i] == '0'){ temp[i] = expr[i]; } if (expr[i] == '1'){ temp[i] = expr[i]; } if (expr[i] == '2'){ temp[i] = expr[i]; } if (expr[i] == '3'){ temp[i] = expr[i]; } if (expr[i] == '4'){ temp[i] = expr[i]; } if (expr[i] == '5'){ temp[i] = expr[i]; } if (expr[i] == '6'){ temp[i] = expr[i]; } if (expr[i] == '7'){ temp[i] = expr[i]; } if (expr[i] == '8'){ temp[i] = expr[i]; } if (expr[i] == '9'){ temp[i] = expr[i]; } if (expr[i] == ' '){ temp[i] = '\0'; sscanf(temp,"%d",&number); index_counter = i+1; //skips? } } // is this included here? temp[i] = '\0'; }

    Read the article

  • How to implement dynamic binary search for search and insert operations of n element (C or C++)

    - by iecut
    The idea is to use multiple arrays, each of length 2^k, to store n elements, according to binary representation of n.Each array is sorted and different arrays are not ordered in any way. In the above mentioned data structure, SEARCH is carried out by a sequence of binary search on each array. INSERT is carried out by a sequence of merge of arrays of the same length until an empty array is reached. More Detail: Lets suppose we have a vertical array of length 2^k and to each node of that array there attached horizontal array of length 2^k. That is, to the first node of vertical array, a horizontal array of length 2^0=1 is connected,to the second node of vertical array, a horizontal array of length 2^1= 2 is connected and so on. So the insert is first carried out in the first horizontal array, for the second insert the first array becomes empty and second horizontal array is full with 2 elements, for the third insert 1st and 2nd array horiz. array are filled and so on. I implemented the normal binary search for search and insert as follows: int main() { int a[20]= {0}; int n, i, j, temp; int *beg, *end, *mid, target; printf(" enter the total integers you want to enter (make it less then 20):\n"); scanf("%d", &n); if (n = 20) return 0; printf(" enter the integer array elements:\n" ); for(i = 0; i < n; i++) { scanf("%d", &a[i]); } // sort the loaded array, binary search! for(i = 0; i < n-1; i++) { for(j = 0; j < n-i-1; j++) { if (a[j+1] < a[j]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } printf(" the sorted numbers are:"); for(i = 0; i < n; i++) { printf("%d ", a[i]); } // point to beginning and end of the array beg = &a[0]; end = &a[n]; // use n = one element past the loaded array! // mid should point somewhere in the middle of these addresses mid = beg += n/2; printf("\n enter the number to be searched:"); scanf("%d",&target); // binary search, there is an AND in the middle of while()!!! while((beg <= end) && (*mid != target)) { // is the target in lower or upper half? if (target < *mid) { end = mid - 1; // new end n = n/2; mid = beg += n/2; // new middle } else { beg = mid + 1; // new beginning n = n/2; mid = beg += n/2; // new middle } } // find the target? if (*mid == target) { printf("\n %d found!", target); } else { printf("\n %d not found!", target); } getchar(); // trap enter getchar(); // wait return 0; } Could anyone please suggest how to modify this program or a new program to implement dynamic binary search that works as explained above!!

    Read the article

  • Custom Memory Allocator for STL map

    - by Prasoon Tiwari
    This question is about construction of instances of custom allocator during insertion into a std::map. Here is a custom allocator for std::map<int,int> along with a small program that uses it: #include <stddef.h> #include <stdio.h> #include <map> #include <typeinfo> class MyPool { public: void * GetNext() { return malloc(24); } void Free(void *ptr) { free(ptr); } }; template<typename T> class MyPoolAlloc { public: static MyPool *pMyPool; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template<typename X> struct rebind { typedef MyPoolAlloc<X> other; }; MyPoolAlloc() throw() { printf("-------Alloc--CONSTRUCTOR--------%08x %32s\n", this, typeid(T).name()); } MyPoolAlloc(const MyPoolAlloc&) throw() { printf(" Copy Constructor ---------------%08x %32s\n", this, typeid(T).name()); } template<typename X> MyPoolAlloc(const MyPoolAlloc<X>&) throw() { printf(" Construct T Alloc from X Alloc--%08x %32s %32s\n", this, typeid(T).name(), typeid(X).name()); } ~MyPoolAlloc() throw() { printf(" Destructor ---------------------%08x %32s\n", this, typeid(T).name()); }; pointer address(reference __x) const { return &__x; } const_pointer address(const_reference __x) const { return &__x; } pointer allocate(size_type __n, const void * hint = 0) { if (__n != 1) perror("MyPoolAlloc::allocate: __n is not 1.\n"); if (NULL == pMyPool) { pMyPool = new MyPool(); printf("======>Creating a new pool object.\n"); } return reinterpret_cast<T*>(pMyPool->GetNext()); } //__p is not permitted to be a null pointer void deallocate(pointer __p, size_type __n) { pMyPool->Free(reinterpret_cast<void *>(__p)); } size_type max_size() const throw() { return size_t(-1) / sizeof(T); } void construct(pointer __p, const T& __val) { printf("+++++++ %08x %s.\n", __p, typeid(T).name()); ::new(__p) T(__val); } void destroy(pointer __p) { printf("-+-+-+- %08x.\n", __p); __p->~T(); } }; template<typename T> inline bool operator==(const MyPoolAlloc<T>&, const MyPoolAlloc<T>&) { return true; } template<typename T> inline bool operator!=(const MyPoolAlloc<T>&, const MyPoolAlloc<T>&) { return false; } template<typename T> MyPool* MyPoolAlloc<T>::pMyPool = NULL; int main(int argc, char *argv[]) { std::map<int, int, std::less<int>, MyPoolAlloc<std::pair<const int,int> > > m; //random insertions in the map m.insert(std::pair<int,int>(1,2)); m[5] = 7; m[8] = 11; printf("======>End of map insertions.\n"); return 0; } Here is the output of this program: -------Alloc--CONSTRUCTOR--------bffcdaa6 St4pairIKiiE Construct T Alloc from X Alloc--bffcda77 St13_Rb_tree_nodeISt4pairIKiiEE St4pairIKiiE Copy Constructor ---------------bffcdad8 St13_Rb_tree_nodeISt4pairIKiiEE Destructor ---------------------bffcda77 St13_Rb_tree_nodeISt4pairIKiiEE Destructor ---------------------bffcdaa6 St4pairIKiiE ======Creating a new pool object. Construct T Alloc from X Alloc--bffcd9df St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d028 St4pairIKiiE. Destructor ---------------------bffcd9df St4pairIKiiE Construct T Alloc from X Alloc--bffcd95f St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d048 St4pairIKiiE. Destructor ---------------------bffcd95f St4pairIKiiE Construct T Alloc from X Alloc--bffcd95f St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d068 St4pairIKiiE. Destructor ---------------------bffcd95f St4pairIKiiE ======End of map insertions. Construct T Alloc from X Alloc--bffcda23 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d068. Destructor ---------------------bffcda23 St4pairIKiiE Construct T Alloc from X Alloc--bffcda43 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d048. Destructor ---------------------bffcda43 St4pairIKiiE Construct T Alloc from X Alloc--bffcda43 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d028. Destructor ---------------------bffcda43 St4pairIKiiE Destructor ---------------------bffcdad8 St13_Rb_tree_nodeISt4pairIKiiEE Last two columns of the output show that an allocator for std::pair<const int, int> is constructed everytime there is a insertion into the map. Why is this necessary? Is there a way to suppress this? Thanks! Edit: This code tested on x86 machine with g++ version 4.1.2. If you wish to run it on a 64-bit machine, you'll have to change at least the line return malloc(24). Changing to return malloc(48) should work.

    Read the article

  • Different standard streams per POSIX thread

    - by Roman Nikitchenko
    Is there any possibility to achieve different redirections for standard output like printf(3) for different POSIX thread? What about standard input? I have lot of code based on standard input/output and I only can separate this code into different POSIX thread, not process. Linux operation system, C standard library. I know I can refactor code to replace printf() to fprintf() and further in this style. But in this case I need to provide some kind of context which old code doesn't have. So doesn't anybody have better idea (look into code below)? #include <pthread.h> #include <stdio.h> void* different_thread(void*) { // Something to redirect standard output which doesn't affect main thread. // ... // printf() shall go to different stream. printf("subthread test\n"); return NULL; } int main() { pthread_t id; pthread_create(&id, NULL, different_thread, NULL); // In main thread things should be printed normally... printf("main thread test\n"); pthread_join(id, NULL); return 0; }

    Read the article

  • How to access a matrix in a matlab struct's field from a mex function?

    - by B. Ruschill
    I'm trying to figure out how to access a matrix that is stored in a field in a matlab structure from a mex function. That's awfully long winded... Let me explain: I have a matlab struct that was defined like the following: matrixStruct = struct('matrix', {4, 4, 4; 5, 5, 5; 6, 6 ,6}) I have a mex function in which I would like to be able to receive a pointer to the first element in the matrix (matrix[0][0], in c terms), but I've been unable to figure out how to do that. I have tried the following: /* Pointer to the first element in the matrix (supposedly)... */ double *ptr = mxGetPr(mxGetField(prhs[0], 0, "matrix"); /* Incrementing the pointer to access all values in the matrix */ for(i = 0; i < 3; i++){ printf("%f\n", *(ptr + (i * 3))); printf("%f\n", *(ptr + 1 + (i * 3))); printf("%f\n", *(ptr + 2 + (i * 3))); } What this ends up printing is the following: 4.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 I have also tried variations of the following, thinking that perhaps it was something wonky with nested function calls, but to no avail: /* Pointer to the first location of the mxArray */ mxArray *fieldValuePtr = mxGetField(prhs[0], 0, "matrix"); /* Get the double pointer to the first location in the matrix */ double *ptr = mxGetPr(fieldValuePtr); /* Same for loop code here as written above */ Does anyone have an idea as to how I can achieve what I'm trying to, or what I am potentially doing wrong? Thanks! Edit: As per yuk's comment, I tried doing similar operations on a struct that has a field called array which is a one-dimensional array of doubles. The struct containing the array is defined as follows: arrayStruct = struct('array', {4.44, 5.55, 6.66}) I tried the following on the arrayStruct from within the mex function: mptr = mxGetPr(mxGetField(prhs[0], 0, "array")); printf("%f\n", *(mptr)); printf("%f\n", *(mptr + 1)); printf("%f\n", *(mptr + 2)); ...but the output followed what was printed earlier: 4.440000 0.000000 0.000000

    Read the article

  • Closing thread using ExitThread - C

    - by Jamie Keeling
    I have a simple program that creates a thread, loops twenty times and then makes a call to close itself and perform the necessary cleanup. When I debug the program it reaches the ExitThread(); method and pauses, ignoring the printf(); I have set up after it to signal to me it's closed. Is this normal or am I forgetting to do something? I'm new to threading using C. Main() void main() { Time t; int i = 0; StartTimer(); for(i = 0; i < 20; i++) { t = GetTime(); printf("%d.%.3d\n", t.seconds, t.milliseconds); Sleep(100); } StopTimer(); } Thread Creation void StartTimer() { DWORD threadId; seconds = 0; milliseconds = 0; // Create child thread hThread = CreateThread( NULL, // lpThreadAttributes (default) 0, // dwStackSize (default) ThreadFunc, // lpStartAddress NULL, // lpParameter 0, // dwCreationFlags &threadId // lpThreadId (returned by function) ); // Check child thread was created successfully if(hThread == NULL) { printf("Error creating thread\n"); } } Thread Close void StopTimer() { DWORD exitCode; if(GetExitCodeThread(hThread,&exitCode) != 0) { ExitThread(exitCode); printf("Thread closed"); if(CloseHandle(hThread)) { printf("Handle closed"); } } }

    Read the article

  • Hi I am facing a fragmentation error while executing this code? Can someone explain why?

    - by aks
    #include<stdio.h> struct table { char *ipAddress; char *domainName; struct table *next; }; struct table *head = NULL; void add_rec(); void show_rec(); int main() { add_rec(); show_rec(); return 0; } void add_rec() { struct table * temp = head; struct table * temp1 = (struct table *)malloc(sizeof(struct table)); if(!temp1) printf("\n Unable to allocate memory \n"); printf("Enter the ip address you want \n"); scanf("%s",temp1->ipAddress); printf("\nEnter the domain name you want \n"); scanf("%s",temp1->domainName); if(!temp) { head = temp; } else { while(temp->next!=NULL) temp = temp->next; temp->next = temp1; } } void show_rec() { struct table * temp = head; if(!temp) printf("\n No entry exists \n"); while(temp!=NULL) { printf("ipAddress = %s\t domainName = %s\n",temp->ipAddress,temp->domainName); temp = temp->next; } } When i execute this code and enters the IP address for the first node, i am facing fragmentation error. The code crashed. Can someone enlighten?

    Read the article

  • Why do i get segfault at the end of the application after everything's been done properly ?

    - by VaioIsBorn
    #include <string.h> #include <stdlib.h> #include <stdio.h> int main(void) { unsigned char *stole; unsigned char pass[] = "m4ak47"; printf("Vnesi password: \t"); scanf("%s", stole); if(strncmp(stole, pass, sizeof(pass)) != 0) { printf("wrong password!\n"); exit(0); } else printf("Password correct\n"); printf("some stuf here...\n\n"); return 0; } This program is working nice, but with one problem - if the password is correct then it DOES do the printing of 'some stuf here...' but it also shows me segmentation fault error at the end. Why ?

    Read the article

  • calling c function from assembly

    - by void
    I'm trying to use a function in assembly in a C project, the function is supposed to call a libc function let's say printf() but I keep getting a segmentation fault. In the .c file I have the declaration of the function let's say int do_shit_in_asm() In the .asm file I have .extern printf .section .data printtext: .ascii "test" .section .text .global do_shit_in_asm .type do_shit_in_asm, @function do_shit_in_asm: pushl %ebp movl %esp, %ebp push printtext call printf movl %ebp, %esp pop %ebp ret Any pointers would be appreciated. as func.asm -o func.o gcc prog.c func.o -o prog

    Read the article

  • Differences between matrix implementation in C

    - by tempy
    I created two 2D arrays (matrix) in C in two different ways. I don't understand the difference between the way they're represented in the memory, and the reason why I can't refer to them in the same way: scanf("%d", &intMatrix1[i][j]); //can't refer as &intMatrix1[(i * lines)+j]) scanf("%d", &intMatrix2[(i * lines)+j]); //can't refer as &intMatrix2[i][j]) What is the difference between the ways these two arrays are implemented and why do I have to refer to them differently? How do I refer to an element in each of the arrays in the same way (?????? in my printMatrix function)? int main() { int **intMatrix1; int *intMatrix2; int i, j, lines, columns; lines = 3; columns = 2; /************************* intMatrix1 ****************************/ intMatrix1 = (int **)malloc(lines * sizeof(int *)); for (i = 0; i < lines; ++i) intMatrix1[i] = (int *)malloc(columns * sizeof(int)); for (i = 0; i < lines; ++i) { for (j = 0; j < columns; ++j) { printf("Type a number for intMatrix1[%d][%d]\t", i, j); scanf("%d", &intMatrix1[i][j]); } } /************************* intMatrix2 ****************************/ intMatrix2 = (int *)malloc(lines * columns * sizeof(int)); for (i = 0; i < lines; ++i) { for (j = 0; j < columns; ++j) { printf("Type a number for intMatrix2[%d][%d]\t", i, j); scanf("%d", &intMatrix2[(i * lines)+j]); } } /************** printing intMatrix1 & intMatrix2 ****************/ printf("intMatrix1:\n\n"); printMatrix(*intMatrix1, lines, columns); printf("intMatrix2:\n\n"); printMatrix(intMatrix2, lines, columns); } /************************* printMatrix ****************************/ void printMatrix(int *ptArray, int h, int w) { int i, j; printf("Printing matrix...\n\n\n"); for (i = 0; i < h; ++i) for (j = 0; j < w; ++j) printf("array[%d][%d] ==============> %d\n, i, j, ??????); }

    Read the article

  • C: switch case with logical operator

    - by Er Avinash Singh
    While I am new to c and want help in this program my code is : #include<stdio.h> #include<conio.h> void main(){ int suite=2; switch(suite) { case 1||2: printf("hi"); case 3: printf("byee"); default: printf("hello"); } printf("I thought somebody"); getche(); } I am working in turbo c and it shows no error and the output is helloI thought somebody Please, let me know how is this working ??? note :- here break is not the case as I intentionally left them.

    Read the article

  • gets (variable)

    - by borlee
    can anyone tell me why gets(abc) works with char[] but not with int? int abc; char name[] = "lolrofl"; printf("Hello %s.\n",name); printf("\n "); fflush(stdin); gets (abc); printf("\n die zahl ist %i.\n",abc); system("Pause"); return(0);

    Read the article

  • Basic C programming question

    - by Amit
    Hi all, I've just started to learn C and it's going pretty slow...I wanted to write a program that takes in an integer argument and returns it's doubled value (aka take in integer, multiply by 2, and printf that value). I purposely did not want to use the scanf function. Here's what I have so far and what is not compiling... #include <stdio.h> int main(int index) { if (!(index)) { printf("No index given"); return 1; } a = index*2; printf("Mult by 2 %d",a); return 0; } So basically when the program is executed I want to supply the index integer. So, in cygwin, I would write something like ./a 10 and 10 would be stored into the index variable. Also, I want to program to return "No index given" and exit if no index value was supplied... Anyone care to help what I'm doing wrong? EDIT: This code returns 1 error upon compilation and is based on the help by @James: #include <stdio.h> int main(int 1, char index) { int index, a; if (!(index)) { printf("No index given"); return 1; } a = index*2; printf("Mult by 2 %d",a); return 0; } Thanks! Amit

    Read the article

  • [Netbeans 6.9] Java MethodOverloading error with double values

    - by Nimitips
    Here is a part of my code I'm having trouble with: ===Class Overload=== public class Overload { public void testOverLoadeds() { System.out.printf("Square of integer 7 is %d\n",square(7)); System.out.printf("Square of double 7.5 is %d\n",square(7.5)); }//..end testOverloadeds public int square(int intValue) { System.out. printf("\nCalled square with int argument: %d\n",intValue); return intValue * intValue; }//..end square int public double square(double doubleValue) { System.out.printf("\nCalled square with double argument: %d\n", doubleValue); return doubleValue * doubleValue; }//..end square double }//..end class overload ===Main=== public static void main(String[] args) { Overload methodOverload = new Overload(); methodOverload.testOverLoadeds(); } It compiles with no error, however when I try to run it the output is: Called square with int argument: 7 Square of integer 7 is 49 Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:3999) at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2709) at java.util.Formatter$FormatSpecifier.print(Formatter.java:2661) at java.util.Formatter.format(Formatter.java:2433) at java.io.PrintStream.format(PrintStream.java:920) at java.io.PrintStream.printf(PrintStream.java:821) at methodoverload.Overload.square(Overload.java:19) at methodoverload.Overload.testOverLoadeds(Overload.java:8) at methodoverload.Main.main(Main.java:9) Called square with double argument:Java Result: 1 What am I doing wrong? I'm on Ubuntu 10.10, Netbeans 6.9. Thanks.

    Read the article

  • how to print a char from struct

    - by make
    Hi Could someone please tell us to print a char when receiving data as a struct? Here is an example: ... struct rcv{ int x1; float x2; char *x3; }; rcv data_rcv; ... if (recv(socket, &data_rcv, sizeof(data_rcv), 0) < 0) printf("recv() failed"); ... printf("x1 = %d\n", data_rcv.x1); printf("x2 = %f\n", data_rcv.x2); printf("x3 = %s\n", data_rcv.x3); // it doesn't print anything, why? ... Thanks for your replies-

    Read the article

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