gerard4143 371 Nearly a Posting Maven

Is there any way to test if a string is an integer without having to convert the C++ string to a C_string?

std::string my_str = "123abc";


for (int i = 0; i < my_str.length(); ++i)
{
if (isdigit(my_str[i]))
{
//do something
}
}
gerard4143 371 Nearly a Posting Maven

Take a look at your braces in your if statement.

Try this

bool checkNumber(int arr[], int value)
{
	for(int i=0; (i < 10); i++)
	{
	  std::cout << arr[i] << std::endl;
		if(value == arr[i])
		{
			return true;	
		}
	}	
	return false;
}
phorce commented: Thank you +2
gerard4143 371 Nearly a Posting Maven

Why are you using a reference to a pointer in your equals operator?

ThuggyWuggy commented: Solved problem, thanks +1
gerard4143 371 Nearly a Posting Maven

Try creating a pipe. Here's a simple example.

#include <iostream>
#include <unistd.h>

enum PIPES {READ, WRITE};

int main(int argc, char**argv)
{
	int hpipe[2];
	pipe (hpipe);

	if (fork())
	{
		close (hpipe[WRITE]);
		
		int x = 0;

		while (true)
		{
			read (hpipe[READ], (char*)&x, sizeof(int));
			if (x < 0) break;	
			std::cout<<"child recieved->"<<x<<"\n";
		}

		close (hpipe[READ]);
	}
	else
	{
		close (hpipe[READ]);
		const int MINUS = -1;

		for (int i = 0; i < 1000; ++i)
			write (hpipe[WRITE], (char*)&i, sizeof(int));
		write (hpipe[WRITE], (char*)&MINUS, sizeof(int));
		close (hpipe[WRITE]);
	}
	return 0;
}
gerard4143 371 Nearly a Posting Maven

Try the escape sequence \" e.g.

std::cout << "this is a quote \"" << std::endl;
gerard4143 371 Nearly a Posting Maven

If the memory manager can fulfill the malloc request it will return a memory pointer to the allocated memory...if it fails it returns NULL.

If malloc returns a pointer other than NULL then you have your requested memory.

gerard4143 371 Nearly a Posting Maven

Try using std::string.

ben1996123 commented: Simple working answer, fast reply. +3
gerard4143 371 Nearly a Posting Maven

Maybe if you tried

if ((scode == "r") || (scode == "R"))
gerard4143 371 Nearly a Posting Maven

I am really sorry! This is my call to Initialize.

List *callInitialize () {

    List *L;

    List studentList;
    L = &studentList;

    Initialize(L);

return L;
}

Your function callInitialize is returning a pointer to a local variable studentList? When callInitialize returns that variable will be invalid memory.

gerard4143 371 Nearly a Posting Maven

I see where your calling callInitialize() but not where your calling Initialize().

gerard4143 371 Nearly a Posting Maven

I just tried your code an it worked for me.

test.c

#include <stdio.h>
#include <stdlib.h>

extern int addus(int,int);

int main() 
{

	int a;
	int b;
	int result;
	a=5;
	b=6;

	result = addus(a,b);
	printf("Your value is: %d", result);
	return EXIT_SUCCESS;
}

asmfile.s//note function label, I changed it to addus

.globl addus
addus:

pushl %ebp
movl %esp, %ebp

movl 8(%ebp), %ecx
addl 12(%ebp), %ecx
movl %ecx, %eax

movl %ebp, %esp
popl %ebp
ret

Compile lines

as asmfile.s --32 -o asmfile.o
gcc test.c -c -m32
gcc test.o asmfile.o -o test -m32

Note I had to use the -m32 and --32 switches because my machine is a Intel 64 bit.

gerard4143 371 Nearly a Posting Maven

Do you mean something like below?

#include <iostream>

class A
{
public:
  virtual void display_it() const { std::cout << "class A" << std::endl; }
protected:
	int x;
};
class B : public A
{
public:
  void display_it() const { std::cout << "class B" << std::endl; }
	int y, z;
};

class C
{
public:
	C(bool derivedClass)
	{
		if (derivedClass)
		{
			pAB = new B;
		}
		else
		{
			pAB = new A;
		}
	}
	
	void whoami() const { pAB->display_it(); }
	
	A* pAB;
	// other members
};

int main(int argc, char**argv)
{
  C one(true);
  C two(false);
  
  one.whoami();//class B
  two.whoami();//class A
  
  return 0;
}
Jsplinter commented: Thank you. Well explained. +3
gerard4143 371 Nearly a Posting Maven

I herd that some C++ compilers can use asembly languige in there programs along side C++, How would I do This? And is there any way to use a compiler as an assembler? <<two questions.

How do you integrate assembly into C++? Generally most compilers provide inline assembly as an extension to the C++ compiler.

How is this accomplished? Most vendors provide a keyword asm or __asm or __asm__ which you can follow with assembly instructions...Here's a link.

http://msdn.microsoft.com/en-us/library/45yd4tzz%28v=vs.71%29.aspx

Is there a way to use the C++ compiler as an assembler? Yes, all C/C++ compilers I used assembled the code.

gerard4143 371 Nearly a Posting Maven

Only if he/she likes a pointer that refers to invalid memory(int 'a' becomes invalid when the function 'check' returns).

dellat commented: Right +0
gerard4143 371 Nearly a Posting Maven

Here's an example that works on my AMD/64 bit machine.

testit.cpp

#include <iostream>

extern "C" int sum(int, int);//to avoid name mangling

int main()
{
	std::cout << sum(3, 4) << std::endl;
	return 0;
}

asm_file.s

.section .data

.section .bss

.section .text
	.global sum
sum:
	pushq	%rbp
	movq	%rsp, %rbp

	xorq	%rax, %rax
	addl	%edi, %eax
	addl	%esi, %eax

	movq	%rbp, %rsp
	popq	%rbp
	ret

objdump -D testit.o>testfile

testfile

testit.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <main>:
   0:	55                   	push   %rbp
   1:	48 89 e5             	mov    %rsp,%rbp
   4:	be 04 00 00 00       	mov    $0x4,%esi //the values and registers we want
   9:	bf 03 00 00 00       	mov    $0x3,%edi //the values and registers we want
   e:	e8 00 00 00 00       	callq  13 <main+0x13>
  13:	89 c6                	mov    %eax,%esi
  15:	bf 00 00 00 00       	mov    $0x0,%edi
  1a:	e8 00 00 00 00       	callq  1f <main+0x1f>
  1f:	be 00 00 00 00       	mov    $0x0,%esi
  24:	48 89 c7             	mov    %rax,%rdi
  27:	e8 00 00 00 00       	callq  2c <main+0x2c>
  2c:	b8 00 00 00 00       	mov    $0x0,%eax
  31:	c9                   	leaveq 
  32:	c3                   	retq

And the compile lines.

g++ testit.cpp -c
as asm_file.s -o asm_file.o
g++ asm_file.o testit.o -o testit

gerard4143 371 Nearly a Posting Maven

Try something like below

#include <stdio.h>
#include <stdlib.h>

unsigned long *lptr = NULL;

int main()
{
  lptr = (unsigned long*)malloc(sizeof(unsigned long));
  
  /*check if allocation failed*/
  
  __asm__ 	(
				"movq	%0, %%rax\n\t"
				"movq	$6, (%%rax)\n\t"
				:"=m"(lptr)
			);
			
  fprintf(stdout, "ans->%lu\n", *lptr);
  return 0;
}
wildplace commented: =D great helpl +2
gerard4143 371 Nearly a Posting Maven

The operating system will use the next lowest file descriptor for that application. It really makes sense if you think about it. Would you expect the operating system to return a random number?

The third value is used if open creates a new file, its the umask value that's applied to the newly created file.

vedro-compota commented: +++++++++++ +1
gerard4143 371 Nearly a Posting Maven

Try compiling this program

testp.c

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char**argv)
{
  char ch;
  FILE *fd = NULL;
  
  if ( argc != 2 )
  {
	fputs("usage error - a.out <Filename>\n", stderr);
	exit(EXIT_FAILURE);
  }
  
  if (!(fd = fopen(argv[1], "r")))
  {
	fprintf(stdout, "Could not open %s\n", argv[1]);
	exit(EXIT_FAILURE);
  }
  
  while (fread(&ch, sizeof(char), 1, fd))
  {
	fprintf(stdout, "%p ", (void*)ch);
  }
  
  fclose(fd);
  return 0;
}

Now pass a file name as a command line argument..It should display the binary(hex values) contents of the file.

gerard4143 371 Nearly a Posting Maven

Line 33.

fprintf(ci,"Amount paid to date: %.2f\n",& info.apaid);

Your passing the address of info.apaid to fprintf.. It should be.

fprintf(ci,"Amount paid to date: %.2f\n", info.apaid);

Also your using fflush() incorrectly, you should never flush an input stream. If you want to flush all possible streams then call fflush(NULL).

gerard4143 371 Nearly a Posting Maven

You have a number of questionable things in that function.

float calcActualAmount(float amountP, int nrChildrenP)
{

  float leftToSpend;
  if (calcAllowedPerChild(nrChildrenP) > 180)
	amountP = 180;
  else if (calcAllowedPerChild(nrChildrenP) < 180)
	leftToSpend = calcAllowedPerChild(nrChildrenP) - 100;
  
  do
  {
	for (int i = 1; i <= 5; i++)
	{
	  switch (i)
	  {
	  case 1: leftToSpend -= TOOTHBRUSH;
	  break;
	  case 2: leftToSpend -= HIGHLIGHTERS;
	  break;
	  case 3: leftToSpend -= CRAYONS;
	  break;
	  case 4: leftToSpend -= NOTEBOOK;
	  break;
	  case 5: leftToSpend -= PEN;
	  break;

	  amountP = calcAllowedPerChild(nrChildrenP) - leftToSpend;/*why are you calling this agin?*/

	  }
	}

  return amountP;
  }
  while (leftToSpend == 0);/*whats the purpose of this?*/
}
gerard4143 371 Nearly a Posting Maven

Here's an example that displays 'Hello, World!'. Note this will only work on a Linux 64 bit PC.

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

unsigned char mya[] = 	{
			  0x50,0x57,0x56,0x52,0xe8,
			  0x00,0x00,0x00,0x00,0x5e,
			  0x48,0x81,0xc6,0x24,0x00,
			  0x00,0x00,0x48,0xc7,0xc0,
			  0x01,0x00,0x00,0x00,0x48,
			  0xc7,0xc7,0x01,0x00,0x00,
			  0x00,0x48,0xc7,0xc2,0x0e,
			  0x00,0x00,0x00,0x0f,0x05,
			  0x5a,0x5e,0x5f,0x5a,0xc3,
			  0x48,0x65,0x6c,0x6c,0x6f,
			  0x2c,0x20,0x57,0x6f,0x72,
			  0x6c,0x64,0x21,0x0a,0x00
			};
			
int main(int argc, char**argv)
{
  void *addr = (void*)((unsigned long)mya & ((0UL - 1UL) ^ 0xfff));/*get memory page*/
  int ans = mprotect(addr, 1, PROT_READ|PROT_WRITE|PROT_EXEC);/*set page attributes*/
  if (ans)
  {
    perror("mprotect");
    exit(EXIT_FAILURE);
  }
  
  ((void(*)(void))mya)();/*execute array*/
  
  return 0;
}
pseudorandom21 commented: Absolutely good, hard to find this information too. +1
ebrahim.amq commented: Hello dear , Please tell me how did you get the raw code of the function? +0
gerard4143 371 Nearly a Posting Maven

You'll have to change the memory attributes of the array to read and execute and then point the instruction pointer at it.

gerard4143 371 Nearly a Posting Maven

1.Is this step must? (since you havnt shown this in first post)
2.After freeing a in that way, why is

free(a)

needed?

You have to understand that each call to malloc returns an individual area of memory that has no association to other calls to malloc, so for each call to malloc you have to call free.

gerard4143 371 Nearly a Posting Maven

Yeah it works, but your using memory that you freed which is a no no.

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
double **memalloc(int M,int N);
int main()
{
  int i,j;  
  double **a;
  a=memalloc(2,2);
  printf("a\n");
  for(i=0;i<2;i++)
    {
      printf("\n");
      for(j=0;j<2;j++)
	{
	  a[i][j]=i+j;
	  printf("%f\t",a[i][j]);	  
	}
    }
	/*free the additional memory here*/
  free(a);

	return 0;
}

double **memalloc(int M,int N)
{
  int i;
  double **y;
  y = malloc(M* sizeof(double *));
  if(y == NULL)
    {
      printf("out of memory\n");
      return 0;
    }
  for(i = 0; i < M; i++)
    {
      y[i] = malloc(N * sizeof(double));
      if(y[i] == NULL)
	{
	  printf("out of memory\n");
	  return 0;
	}
      free(y[i]);/*don't free the memory here*/	  
    } 

  return y;
}
gerard4143 371 Nearly a Posting Maven

Inclusion guards are a good example of usage.

http://en.wikipedia.org/wiki/Include_guard

gerard4143 371 Nearly a Posting Maven

When you need dynamic memory, trees, lists, passing large objects to functions.

gerard4143 371 Nearly a Posting Maven

Here's an example that uses enough functionality to answer your questions.

#include <stdio.h>
#include <string.h>

#define ARR_SIZE 100

int main()
{
	size_t i = 0;
	size_t size = 0;
	char str[ARR_SIZE];

	fputs("Enter a string->", stdout);
	fgets(str, ARR_SIZE, stdin);

	size = strlen(str);

	for (i = 0; i < size; ++i)
		fputc(str[i], stdout);
	return 0;
}
gerard4143 371 Nearly a Posting Maven

I'm wondering what is the proper way to point at an overloaded function. Is it correct to cast the function to the proper type?

#include <iostream>

int double_it(int x)
{
	return x * 2;
}

int double_it(int x, int y)
{
	return (x + y) * 2;
}


int main(int argc, char**argv)
{
	void *myfunc = (void*)(int(*)(int))double_it;
	return 0;
}
mike_2000_17 commented: nice question +2
gerard4143 371 Nearly a Posting Maven

Here's a general rule about malloc - The number of times that you call malloc, is the the number of times that you have to call free. Your program creates a memory leak by free'ing a before free'ing the other allocated memory areas.

And your error

free(a);

This was pointed out previously.

When you write programs that allocate and free memory, you should run them with a program like valgrind to ensure your not creating memory leaks.

Also, in C the main function is defined as

int  main()
{
/*...*/
return 0;
}
gerard4143 371 Nearly a Posting Maven

C doesn't have objects. The closest thing is a C-string which is an array of characters terminated by '\0'.

char str1[] = "this is a string";/*compiler adds the '\0'*/
char *str2 = "this is another string";/* but its non mutable and the compiler adds the '\0'"*/
char str3[] = {'s','t','r','i','n','g','\0'};/*another string*/
char str4[]  = {'n','o','n'','-','s','t','r','i','n','g'};/*not a string no '\0'*/
WaltP commented: Good list. Esp adding #4... +15
gerard4143 371 Nearly a Posting Maven

tried that also. still error persists

Why are you free'ing y and then returning it?

vineeshvs commented: good ans +1
gerard4143 371 Nearly a Posting Maven

Oh thanks a lot Gerad !!!!
Can u show me the final code with the loop ?

How about you show us the final code.

gerard4143 371 Nearly a Posting Maven

Try looking at the code below..You should be able to finish it with this hint..

#include <iostream>

int main(int argc, char *argv[])
{
    int count_one = 1;
    int count_two = 10;
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < count_one; ++j)
        {
            std::cout << '*';
        }
        for (int j = 0; j < count_two; ++j)
        {
            std::cout << '+';
        }
        ++count_one;
        --count_two;
        std::cout << std::endl;
    }
    return 0;
}
gerard4143 371 Nearly a Posting Maven

You should mark this a solved.

gerard4143 371 Nearly a Posting Maven

Try this

double sum = accumulate(a.begin(),a.end(),0.0);
gerard4143 371 Nearly a Posting Maven

Line 15

int input(worker_t*);
gerard4143 371 Nearly a Posting Maven

Sorry, I take that back; must only apply to 'c'; Just tired it on VC++6 and it worked.

Again, are you sure about your statement?

gerard4143 371 Nearly a Posting Maven

the for statement can't use floating point types as the variant. You are allowed integers and enumeration types.

Are you sure about your statement?

gerard4143 371 Nearly a Posting Maven

You can't allocate memory to the end of your array. You must allocate the new memory and then copy the existing array into the new memory and then finally delete the old memory.

gerard4143 371 Nearly a Posting Maven

The GCC compiler has this option built in, just compile with this option

-ftime-report

example:

g++ filename.cpp -ftime-report -o filename

gerard4143 371 Nearly a Posting Maven

Narue beat me to the punch...Here's my simple solution

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ARR_SIZE 16
#define LOW 0
#define HIGH 15

int mya[ARR_SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

int main(int argc, char**argv)
{
	int i = 0;
	int j = 0;
	int count = 0;
	int index = 0;
	time_t seconds;
	time(&seconds);
	srand((unsigned int) seconds);

	for (; i < ARR_SIZE; ++i, ++count)
	{
		index = rand() % (HIGH - LOW + 1 - count) + LOW;
		fprintf(stdout, "ans->%d\n", mya[index]);
			
		for (j = index; j < (ARR_SIZE - 1); ++j)
		{
			mya[j] = mya[j + 1];
		}
	}

	exit(EXIT_SUCCESS);
}
gerard4143 371 Nearly a Posting Maven

I would use an if statement

if (some condition)
{

}
else if (some other condition)
{

}
else if (more conditions)
{

}
else
{

}
gerard4143 371 Nearly a Posting Maven

Not to steal some of the spotlight from the thread, but I'm confused by what you mean when you say this.

Most languages have facilities that allow you to extend the language..These features are usually implemented in C. Python is a good example of this.

gerard4143 371 Nearly a Posting Maven

What do you mean by that?

Header files shouldn't assume anything. They should be simple and plain...without any preconceptions...we can't assume that the programmer will state 'using namespace std'.

Please read Accelerated C++ or Ruminations on C++ or C++ Primer...All these books state, that header files should be unqualified.

jonsca commented: Agreed +6
gerard4143 371 Nearly a Posting Maven

In this task you don't have remove the vowels just don't write them to the new file. Just be sure to read the input file one character at a time. If the character is a vowel the do nothing, if the character is not a vowel then write it to the output file.

gerard4143 371 Nearly a Posting Maven

Try going at it like this...

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>


int main()
{
  
	char line[50];
	int count = 0;
	char c;

	while((c = getchar() )!= '\n')
	{
		line[count++] = c;
	}

	line[count] = '\0';
	printf("you entered: %s\n",line);

	char *p = line;
	char *start = line;/*save the start of a word*/
	char *mya[100];
	int argCount = 0;

	while(*p)
	{ 
		if(*p == ' ')
		{
			*p = '\0';
			mya[argCount] = start;
			argCount++;
			start = p + 1;/*next starting position*/
		}
		p++;
	}

	mya[argCount] = start;/*assign last one*/

	fprintf(stdout, "%s\n", mya[0]);
	fprintf(stdout, "%s\n", mya[1]);
	fprintf(stdout, "%s\n", mya[2]);
	fprintf(stdout, "%s\n", mya[3]);
	return 0;
}
gerard4143 371 Nearly a Posting Maven

I cleaned your code up a little...well a lot

#include<pthread.h>
#include<stdio.h>
#include<sys/types.h>
#include<semaphore.h>
#include<unistd.h>

pthread_t t1,t2;
pthread_attr_t tattr;
int counter;
sem_t mutex;

void* runner(void *arg)
{
	int i = 0;

	printf("Thread received %i\n", *(int*)arg);

	for(i = 0; i < 5; i++)
	{
		sem_wait(&mutex);
		printf("Thread %i says %i\n",*((int *)arg),counter);
		counter++;
		sem_post(&mutex);
		sleep(1);
	}
	return (void*)NULL;
}

int main()
{
	int r;
	int t = 1;

	printf("hi");
	r = sem_init(&mutex,0,1);
	r = pthread_attr_init(&tattr);

	r = pthread_create(&t1,&tattr,runner,(void *)&t);

	t = 2;

	r = pthread_create(&t2,&tattr,runner,(void *)&t);

	printf("Threads initialised");
	r = pthread_join(t1,NULL);
	r = pthread_join(t2,NULL);
	r = sem_destroy(&mutex);

	return 0;
}

P.S.

This is a pet peeve of mine

r=sem_destroy(&mutex);

It makes the code impossible to read, please consider a more readable format like below.

r = sem_destroy(&mutex);

compile line:
gcc test.c -Wall -ansi -pedantic -o test -pthread

gerard4143 371 Nearly a Posting Maven

The library name is stdio.h not studio.h

gerard4143 371 Nearly a Posting Maven

Try something like below

#include <stdio.h>
#include <string.h>

char data[] = "Hello, World!";
const char *delimiters = " ";  

void function (char* array [])
{
	array[0] = strtok (data, delimiters);

	fprintf(stdout, "first string->%s\n", array[0]);

	array[1] = strtok(NULL, delimiters);

	fprintf(stdout, "second string->%s\n", array[1]);
}

int main () 
{
	char* array[2];
	function(array);

	fprintf(stdout, "first string->%s\n", array[0]);

	fprintf(stdout, "second string->%s\n", array[1]);

	return 0;
}
gerard4143 371 Nearly a Posting Maven
#include<stdio.h>
int main()
{
        int i,j,pass;
        char p[3][10],temp[1][10];
        temp[0]='\0';
        printf("please enter 3 words\n");
        for(i=0;i<3;i++)
        {
                scanf("%s",&p[i]);

        }

        for(pass=0;pass<3;pass++)
        {
                for(i=0;i<3;i++)
                {
                        j=0;

                        repeat:if(p[i][j]<p[i+1][j])
                               continue;
                               else if(p[i][j]>p[i+1][j])
                               {
                                        temp[0]=p[i];
                                        p[i]=p[i+1];
                                        p[i+1]=temp[0];
                               }
                               else
                               {
                                        j++;
                                        goto repeat;
                               }
                }
        }
        for(i=0;i<3;i++)
        {
                printf("%s\n",p[i]);
        }
        return 0;
}

I'm pretty sure that your line 10

scanf("%s",&p[i]);

Is just as dangerous gets().

Try running this program

#include<stdio.h>

int main()
{
	char b[] = "test this";
	char a[10];
	

	fputs("enter a long word like Pseudopseudohypoparathyroidism->", stdout);
	scanf("%s", a);

	fprintf(stdout, "a->%s\n", a);
	fprintf(stdout, "b->%s\n", b);	
	return 0;
}

The output on my machine was

a->Pseudopseudohypoparathyroidism
b->parathyroidism

which indicates a buffer overflow.

Mouche commented: Good example of buffer overflow +5