Go Premium for a chance to win a PS4. Enter to Win

x

C

22K

Solutions

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.

Share tech news, updates, or what's on your mind.

Sign up to Post

Constraint: Cannot change from C++03 or C-88.

After some online search, I wrote the following program to see how to run a class non-static member function in a pthread via a static member helper. But I got the wrong answer. According to breakpoints, the DoSomething constructor is called once; yet on the 2nd call to doSomething, the initial values of val1 and val2 are set to 100, 200.0, respectively. Granted, I set the members of an internal struct to those values, but not to the class data members.

So, how did that happen; how do I get the args.retval return value from the pthread to end in 5 + 16 = 21 + a multiple of 100.
// header
class DoSomething
{
public:
	DoSomething(int v1, float v2)
		: val1(v1), val2(v2) {
	retval = val2 - val1;
	}

	float* doSomething(int v1, float v2) 
	{
		val1 += v1;
		val2 += v2;
		retval = val1 + val2;
		return &retval;
	}

	struct v1v2_s
	{
		int v1;
		float v2;
		float retval;
	};

	static
    void* DS_helper(void* args)
	{
		int v1 = ((v1v2_s*)args)->v1;
		float v2 = ((v1v2_s*)args)->v2;
		((v1v2_s*)args)->retval = *((DoSomething*)args)->doSomething(v1, v2);
		return args;
	}

private:
	int val1;
	float val2;
	float retval;
};

Open in new window

#include "DoSomething.h"

int main()
{
	DoSomething DS(2, 9);

	DS.doSomething(3, 7);

	DoSomething::v1v2_s args = {100, 200.0};

	pthread_t t;
	pthread_create(&t, NULL, DS.DS_helper, &args);
	pthread_join(t, (void**)&args);
	float res = args.retval;
	return 0;
}

Open in new window


If you could correct the existing code w/o trying to revamp the whole approach, I would appreciate that. (After this is done, then, sure, revamp the whole approach.)
Thanks in advance.
0
Independent Software Vendors: We Want Your Opinion
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

This isn't really a question; rather, it is a puzzle!!!

Please note, this is NOT an assignment of any kind (check my profile if you are unsure as to my tenure on the site). The idea is to spark some activity in the C/C++ topic areas and to have a little fun. Points will be awarded to the expert(s) who provide the most interesting solution. The idea is to have a little fun, promote discussion and have something interesting to think/talk about.

If this goes well, I plan on doing one of these types of puzzle questions on a regular(ish) basis. I would like to see expert colaboration, rather than experts just going gun-ho to get points. I will consider colaboration between experts when I finally award points. I will close this question once I believe it has reached a natural conclusion (ie. no futher productive activity).

So, let's start with the first puzzle. It's one that has been set many times before and I'd be interested in seeing different approaches to solving it. Please don't just search Google and copy/paste. I promise I will check and any plaigirised answers will be ignored (and probably deleted).

Let's go...

Your job is to write a program that, when run, outputs it's own source code (including comments) such that if the output was fed back into a compiler, built and run it would do exactly the same thing as the original program. The output must be word for word identical to the original source code, such that performing a diff between the original source …
1
I have a tcp server running on linux and bound to unix domain socket

I want to allow (give permission ) to another process (running as a user) to connect to the server using the same domain socket.

How Can I achieve that ?


Thanks
0
--------------------Configuration: StockCharter - Win32 Release--------------------
Compiling...
StdAfx.cpp
C:\Program Files (x86)\Microsoft Visual Studio\VC98\INCLUDE\objbase.h(435) : error C2664: 'memcmp' : cannot convert parameter 1 from 'const struct _GUID *' to 'void *'
        Conversion loses qualifiers
C:\Program Files (x86)\Microsoft Visual Studio\VC98\INCLUDE\objbase.h(459) : error C2664: 'memcmp' : cannot convert parameter 1 from 'const struct _GUID *' to 'void *'
        Conversion loses qualifiers
C:\Program Files (x86)\Microsoft Visual Studio\VC98\INCLUDE\memory.h(68) : error C2733: second C linkage of overloaded function '_memccpy' not allowed
        C:\Program Files (x86)\Microsoft Visual Studio\VC98\INCLUDE\memory.h(68) : see declaration of '_memccpy'
C:\Program Files (x86)\Microsoft Visual Studio\VC98\INCLUDE\memory.h(69) : error C2733: second C linkage of overloaded function 'memchr' not allowed
        C:\Program Files (x86)\Microsoft Visual Studio\VC98\INCLUDE\memory.h(69) : see declaration of 'memchr'
C:\Program Files (x86)\Microsoft Visual Studio\VC98\INCLUDE\memory.h(70) : error C2733: second C linkage of overloaded function '_memicmp' not allowed
        C:\Program Files (x86)\Microsoft Visual Studio\VC98\INCLUDE\memory.h(70) : see declaration of '_memicmp'
C:\Program Files (x86)\Microsoft Visual Studio\VC98\INCLUDE\memory.h(76) : error C2733: second C linkage of overloaded function 'memcmp' not allowed
        C:\Program Files …
0
I wrote the attached code with the intention to get 42 as the output but I instead get an asterisks (*) I know that 42 is the ACII value of an asterisk. Please look at my code and see something I might have missed. The program is in C using the <unistd.h> library, I have to use the unistd.h and not the stdio.h for this code.

[code]
#include <unistd.h>

void      ft_putchar(char c)
{
      write(1, &c, 1);
}

void    ft_putnbr(int nbr)
{
    write(1, &nbr, 1);
}

void      ft_ft(int *nbr)
{
      *nbr = 42;
}

int      main(void)
{
      int a;
      int *ptr;
      char c;

      a = 7;
      ptr = &a;
      ft_ft(ptr);
    ft_putnbr(a);
      ft_putchar('\n');
}
/code]
0
Good morning,
im getting the error show in the picture bellow, I've seen other examples and it should work, am I doing something wrong?

error.png
my model
 public class Usuario
    {
        public int Id { get; set; }
        
        [Required]
        [StringLength(80)]
        public string Nombres { get; set; }

        [Required]
        [StringLength(40)]
        [Display(Name ="Primer apellido")]
        public string PrimerApellido { get; set; }

        [Required]
        [StringLength(40)]
        [Display(Name = "Segundo apellido")]
        public string SegundoApellido { get; set; }

        [Required]
        [StringLength(30)]
        public string Cedula { get; set; }

        [Required]
        [Display(Name = "Fecha nacimiento ")]
        public DateTime FechaNacimiento { get; set; }

        [Required]
        [StringLength(5)]
        public string Rh { get; set; }

        [Required]
        [StringLength(10)]
        public string Genero { get; set; } 

        [Required]
        [StringLength(200)]
        [Display(Name = "Dirección")]
        public string Direccion { get; set; }

        [Required]
        [StringLength(200)]
        [Display(Name = "Barrio")]
        public string Barrio { get; set; }

                
        public Municipio Municipio { get; set; }

        [Display(Name = "Municipio")]
        public int MunicipioId { get; set; }
        

        [Display(Name ="Telefono fijo")]
        public string 

Open in new window

0
I have not done unit testing for a little while and expect a test upcoming to verify I can quickly write unit tests.

Suggestions of the thing I should be practicing?

Unit tests generate their own mock data, but I doubt a test would include me setting up a mocking framework. I think hard coded lists of objects would be the ideal method, on a coding test.

I assume the object wold be written already for me (it's going to be a 15 minutes test only)

I would create an instance of the object, review the parameter list for that method being tested...

I could create multiple sets of test data. Would a switch statement be appropriate for this kind of knock em out unit test? I could iterate through and handle a handful of test conditions...


Assertions are key.

Once it fails, the unit test fails. I need to be sure the specific test condition which failed the assertion is visible in the console.

Am I approaching this test the right way?

Suggestions?

Thanks.
0
#include <stdio.h>

int main (void)
{
    printf ("Hello, world!\n");
    return 0;
}


what does the  "\n" below mean ?

printf ("Hello, world!\n"
0
I am working on a project here where I need to have a rolling average of a 2D array of numbers. The rolling average should average across a rolling "window" size of 8. I have a simple example here to demonstrate, but the idea is that with each new 2D array (a new data scan), that array will be copied into the rolling buffer that I have set up as a 3D array where the 3rd dimension is of size of the rolling window. With the current code I have below, I'm not getting the output I expect. To check if its working, I am just printing out the same position in each 2D scan across all scans of the rolling buffer, but I am not getting what I expect and I'm struggling to find issue in the code. Am I even going about this correctly? Thanks for any help. output attached below.

output from current code
I would expect an output that looks like:
0
1 | 0
2 | 1 | 0
3 | 2 | 1 | 0
and so on ...


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlockCopySample
{
    class Program
    {

        static void Main(string[] args)
        {

            RollingAverager RA = new RollingAverager();

            for (int i = 0; i < 25; i++)
            {
                RA.addValue(i);
                RA.PrintBuffer();

                System.Threading.Thread.Sleep(1000);
            }
        }
    }



    class RollingAverager
    {
        const int INT_SIZE = 4;
        const int DOUBLE_SIZE = 8;

    

Open in new window

0
How to do Windows 10 Microsoft Visual Studio 2010 Multihreading (but not .net and not MFC) in C++03.
I don't have 3rd party tools like openMP, etc. Just have native Microsoft API (I hope).

I searched around and found an answer to the following 3 questions (included in my post below):
When I search online, I found this:
Multithreading with C and Win32
https://msdn.microsoft.com/en-us/library/y6h8hye8.aspx

But I am in a 64-bit environment.

a. Is there a Microsoft 64-bit (non .NET) multithreading capability? If not, then I will proceed with 32-bit API. But the applications being developed are 64-bit.

b. Is it OK to use Win32 in the 64-bit application?

c. If it is OK, are there any performance penalties or any other downsides in doing this?

If you explain things to me, and use POSIX terminology and their Microsoft equivalent, that would help. I have done Linux multithreading. I am brand new to Microsoft development (other than using VIsual Studio 2010 for relatively simple single-threaded programs).

Unfortunately, I cannot use C++11 or Boost because they will not be installed for awhile (anywhere between 6-90 months is my best guestimate).

I am unable to install anything to enhance my development. (I know - this sucks.)

1. I would appreciate if you could provide good learning examples and help me with some questions on the basics if they arise.

Here are some links that I have just  quickly …
0
What does it mean to be "Always On"?
LVL 5
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

I am trying to create a C function that will return a string as BSTR so I can use it in VBA and i have broken down into its absolute simplest form. This just accepts one double (I will eventually need 3 doubles). I just need to know how to convert myStr to BSTR and then make it available to a VBA call.
double _stdcall square(double *x)
{
	char myStr[] = "Hello World";
	return *x * *x;
}

Open in new window


In arriving at the above I found found the following code would crudely give me a string back but only the first part does so correctly.  
STDAPI GetMyCode(BSTR in, BSTR out, int cch, double *int1, double *int2, double *int3)
{
	LCMapStringW(LOCALE_USER_DEFAULT, LCMAP_LINGUISTIC_CASING | LCMAP_UPPERCASE, in, SysStringLen(in), out, cch);
	char myStr[60];
	strcpy_s(myStr, 60, out);
	return S_OK;
}

Open in new window


When I convert this code into a DLL and call it with the following VBA, the result is "HÉLLO WORLD" - Absolutely perfect.  
GetMyCode StrPtr("héllo world"), StrPtr(cch), 256, -32.12345, 115.11111, 23.5
debug.print cch

Open in new window

 However the part of the code that isn't compiling correctly is strcpy_s(myStr, 60, out); I assume because out is a BSTR and myStr is char. So I need to work out how to get the value of myStr out of the function into VBA.  Can anyone help me figure out

By way of background:
The function I want to eventually create from this will only take 3 doubles as parameters - the other 3 I have used in this demo are unnecessary.
Eventually myStr will contain a character string (I believe that's know as an array in C) that is somewhere between 9 and 60 characters long
It is that string that I will want to convert to BSTR and return to the VBA call.
But for now, all I need is to just get the above to work.
0
Hey there guys.

I have been given a chunk of C++ Code that I need to turn into assembly for 3 Processors.

The, 6805, DS89C420 & ARM7

Below is the code.
Any Help would be amazing.

void BubbleSort (void) {
 unsigned char tmp;
 int i, j;
 for (i=0; i<sizeof(Data)-1; i++) {
 for (j=0; j<sizeof(Data)-1-i; j++) {
 if (Data[j+1] < Data[j]) {
 tmp = Data[j];
 Data[j] = Data[j+1];
 Data[j+1] = tmp;
 }
 }
 }
 }
0
What options are there to protect a web service from a DOS attack?

IF the web service were accessed only by my Objective-C iPhone application, and nowhere else, is this web service protected by the "security through obscurity" model? Or, can hackers crack open the source code of the iPhone app, like Apple can?

What about if I put the URL to the web service into the SQLite database and encrypted the Path?

So, when my app needs to request information from the web service, it does a DB lookup in the SQLite database for the path to the web service. When it gets it, it decrypts it. Then, using a variable (in memory) only, it makes the web service call.

Does this protect from a DOS attack to that web service call?

Are there easier ways?

Will this work on Java for the Android?

What about on my website?

Thanks.
0
After almost two weeks trying to resolve this I am stumped at what I think is the final step. I just can't come to grips with how I can get a C Function to output a character string and I just don't know how to proceed. In summary I have a function that will generate the string I need

 main()
{
	char buf[60] = { '\0' };   // Set the max length of the final link string
	int ret = GenShortDroidMapUrl(-32.1458637, 115.8353645, (double)14, "my Place", buf, sizeof(buf) - 1);
	buf[ret] = '\0';
	printf("\n return of GenShortDroidMapUrl =  %s \n", buf);
	return 1;
}

Open in new window

When I run this code it displays the code I am after perfectly, but what it is displaying is the value of buf, which is destroyed as soon as this code is run.

I have also been able to create a DLL from it and it builds without errors. In doing so I left out Main() because what I want to do is make a call to this code from MS Access to get the output. In access I added the following which I believe should enable me to make a call to the function GenShortDroidMapUrl and get the response back

Public Declare Function GenShortDroidMapUrl _
    Lib "D:\Rob\source\repos\Ge0Make\Debug\Ge0Make.dll" _
    (ByVal latit As Double _
    , ByVal longit As Double _
    , ByVal zoom As Double _
    , ByVal locName As String _
    , ByRef newurl As String _
    , length60 As Integer)

Open in new window


What I don't know is how to make my C Function output the value of buf when I make the call. I won't put all the code but the GenShortDroidMapUrl function code is as follows. Clearly it returns an int whereas I actually want it to return the string contained in the array buf. And I need it to survive long enough to be handed back to the calling function. I have seen this kind of code work with numbers but I can't get my head around how to do it with a string. Am I missing just a few, short, simple changes that an Expert can help me with, or do I need to employ a C programmer to help me get this DLL working?


Open in new window

0
I want to install WAMP on my laptop to work on a Wordpress site locally to be moved to a server later.  I have all the latest Windows updated and Visual Studio 2017 updates but when I go to wampserver.com/en and download, I get warnings before installing to make sure I am up to date in the redistributable packages vc9, vc10, vc11, vc13, and vc14.  Do I need to install all of those. There is now vc15 which is backward compatible with vc14.  I'm just looking for the easiest and quickest way to set up my WAMP server so I can install wordpress.  I have never installed WAMP or Wordpress on this computer so other than installing other software, I'm really building from scratch.  Also, I considered installing the C# version of WAMP since I work with C#.  Is there any advantage or disadvantage to doing that since I plan to run Wordpress?  Feedback?
0
I have found a C function that I think will provide the results I need but I have zero experience with C. For the sake of explanation, basically I want to input something like  MapsWithMe_GenShortShowMapUrl(-32.1458637, 115.8353645, 14, "my Place") and have it return the full URL formated as needed by the app it's associated with.  

I have taken the C code and tried to incorporate it into a Visual Studio 2017 project as a starting point. I have attached a copy of the entire code and what I am trying to work out is what it is expecting from the buf and bufsize parameters in the line:
   int MapsWithMe_GenShortShowMapUrl(double lat, double lon, double zoom, char const * name, char * buf, int bufSize)
Can anyone help me figure out what parameter it is asking for?

#include <stdio.h>

void main()
{
	
	printf(MapsWithMe_GenShortShowMapUrl(-32.1458637, 115.8353645, 14, "my Place", 1, 1));
}

//#include "api-client.h"
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

// Max number of base64 bytes to encode a geo point.
#define MAPSWITHME_MAX_POINT_BYTES 10
#define MAPSWITHME_MAX_COORD_BITS (MAPSWITHME_MAX_POINT_BYTES * 3)



char MapsWithMe_Base64Char(int x)
{
	assert(x >= 0 && x < 64);
	return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"[x];
}

// Map latitude: [-90, 90] -> [0, maxValue]
int MapsWithMe_LatToInt(double lat, int maxValue)
{
	// M = maxValue, L = maxValue-1
	// lat: -90                

Open in new window

0
Hello ,


I want to create a function to remove an element from IP4Map with matching ip4 but i could not succeded should any body help me ?



typedef struct IP4SYN{
     unsigned int ip4;
     unsigned int count;
	 unsigned int source_port;
	 unsigned int dest_port;
	 unsigned int dest_IP;
     long int SYN_Son;
     size_t s;
     size_t n;
} IP4SYN;

typedef struct IP4Map{
      IP4SYN * a;
      size_t s;
      size_t n;
} IP4Map;
unsigned int AddIP4ToMap(IP4Map * ip4map,unsigned int ip4,unsigned int source_port,unsigned int dest_port,unsigned int dest_IP){
       unsigned int pos =  0;
       if (ip4map->n >= ip4map->s)
       {
              ip4map->a = (IP4SYN *)krealloc( ip4map->a, ip4map->s+blocksize,GFP_NOWAIT);
              memset(&ip4map->a[ip4map->s], 0, sizeof(IP4SYN)*blocksize);
              ip4map->s += blocksize;
       }
       pos = FindIP4InMap(ip4map, ip4,source_port,dest_port,dest_IP);
       if (ip4map->n > pos)
       {
             if((ip4map->a[pos].ip4==ip4)&&(ip4map->a[pos].source_port==source_port)&&(ip4map->a[pos].dest_port==dest_port)&&(ip4map->a[pos].dest_IP==dest_IP)){
					ip4map->a[pos].SYN_Son=Zaman_MS();
					return ++ip4map->a[pos].count;  // increment counter
             }
             else  // shift entries 1 to the right from pos 
             {
                    unsigned int shift = (ip4map->n - pos)-1;
                    if (shift > 0)
                    {
                          memmove(&ip4map->a[pos+1], 

Open in new window

0
Hello  ,

I am trying to read an hex part as given below i am hitting firs 08 with if it is ok than getting the size with 0a -> 10 it is also ok but i couldnot get into a variable .


  08 0a 59 97 a9 ef 07 29 c3 28                    

Open in new window


                        if (kind == 8) {
					p++;
					uint8_t size = *p;
					p++;
					TS=(*(uint32_t *)p)
					//printk(KERN_ERR "4. TS %d ",(*(uint32_t *)p));
					p += (size-2);
				}

Open in new window

0
Hello ,

Normally we really love of using std::map on userspace but in kernel space i could not find a dynamic memory allocated map structure. Any body knows a good example how to do this job on kernel space ?

Thank you
0
Industry Leaders: We Want Your Opinion!
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Hello ,

Is there any library to trace / ping an ip or a better / faster way to get the ttl of an ip address ?
0
With the help of some Experts on other questions I have been led to the following links that generate a URL that will launch maps.me app on Android and iOS devices to a desired GPS Lat, Long, Name and Zoom level. (e.g. -32.1458637,115.8353645, "My Place", 14) . I have a need to generate this URL from MS Access.

Two questions:
1) Is there is any way I could use or set up the existing C function or API to enable me to make a call from MS Access and have it return the URL instead of trying to translate the function into VBA?
2) It would also be useful if I could set it up so I could make a JSON call to it from another app so is there a way I can do that.

    https://www.programcreek.com/java-api-examples/index.php?source_dir=cgeo-master/mapswithme-api/src/com/mapswithme/maps/api/MwmRequest.java           
or
https://github.com/mapsme/omim/blob/master/api/src/c/api-client.c
0
Hello ,

I want to use given struct in a map as this : std::map<Web_Dumper, int> http_dumper;


but i am getting errors, where should i do mistake ?

struct Web_Dumper
{
    IP4 ip;
    const std::string Agent;
    const std::string Version;
    const std::string Host;
    const std::string Path;
    const std::string Ulke;
    long int Tarih;
    Web_Dumper(IP4  szip,const std::string sAgent,const std::string sVersion,const std::string sHost,const std::string sPath,const std::string sUlke,long int sTarih) : 
    ip(szip), Agent(sAgent) , Version(sVersion), Host(sHost), Path(sPath),Ulke(sUlke), Tarih(sTarih){}
    friend bool operator<(const Web_Dumper & ipt1, const Web_Dumper & ipt2) { return std::make_pair(ipt1.ip,ipt1.Agent,ipt1.Version,ipt1.Host,ipt1.Path,ipt1.Ulke,ipt1.Tarih) <  std::make_pair(ipt2.ip,ipt2.Agent,ipt2.Version,ipt2.Host,ipt2.Path,ipt2.Ulke,ipt2.Tarih); }
};

Open in new window




AnomalyDetector.c: In function ‘bool operator<(const Web_Dumper&, const Web_Dumper&)’:
AnomalyDetector.c:1311:173: error: no matching function for call to ‘make_pair(const IP4&, const string&, const string&, const string&, const string&, const string&, const long int&)’
     friend bool operator<(const Web_Dumper & ipt1, const Web_Dumper & ipt2) { return std::make_pair(ipt1.ip,ipt1.Agent,ipt1.Version,ipt1.Host,ipt1.Path,ipt1.Ulke,ipt1.Tarih)
                                                                                                                                   

Open in new window

0
Hello ,

I want to appy a system command with arguments from variables but i could not find an example any body has experience about this ?


This is what i want to do
system("/bin/bash  /etc/a.sh   %d %d",val1,val2);
0
I am testing the authorized.net captureprviouslyauthorizedamount i can get an transaction type as authorization only but can not get the capture amount. it is saying invalied transaction id. Do i need to change from test to production and than cancel the credit card amount
0
How to write test case for c program
0

C

22K

Solutions

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.