9868 35 Light Poster

Hello everyone,
Here's my code for making a dynamic array(the user inputs the size of the array). It's working fine but I think that I've not made the best code. Is there any suggestion for improvement or optimization?

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
	int *p;
	int n,i;
	printf("how many integers do u wanna enter\n");
	scanf("%d",&n);
	p=malloc(n*sizeof(int));
	for(i=0;i<n;i++)
	{
		printf("enter the %d element",i+1);
		scanf("%d",p);
		p++;
	}
	p=p-n;
	for(i=0;i<n;i++)
	{
		printf("%d\n",*(p+i));
	}
	free(p);
}
9868 35 Light Poster

I dont think so.

9868 35 Light Poster

sum()
integer x,y,z
read x,y
z=x+y
print"the sum of x and y is",z
end sum()

Oh man, this is really funny. The OP is asking for elapsed time and you're telling him/her to add two integers.

9868 35 Light Poster

Use strtok().

9868 35 Light Poster

Associativity? I don't even think you got that right if you were trying to say precedence.

Isn't the precedence of * and ++ same, that's why we look for the associativity in *p++ whcih is right to left.

9868 35 Light Poster

hey friends this problem is definately hurting me !! its happening all the time now listen to this !!
i changed the display screen of turo C from full screen to normal window view made a program nd run it !! afterwards it returned ack to that full screen and then when i tried to exit from that turbo C IDE again it was blank !! this is a killing problem !!

Try to reinstall TC.

9868 35 Light Poster

1. Use code tags.
2.

scanf("&c", &code);

3. Your do while will print invalid code even if someone inputs a valid code.
4. Use switch statements instead of if-else.
5. For double I think the format specifier is %f only and not %lf, but not sure.
6. Indent your code properly.

9868 35 Light Poster

1.You're not creating the string properly. status==OUT.
2. If you make the string properly then also the makenode function is not correct, you need to pass the characters of the string one by one, not the whole string at a time. In your case there are no left and right subtrees getting created.
3. Why do you need to create a string by the way. Simply input all the integers and make a tree from that. I mean make a BST from the array, then do inorder traversal, it will sort the list.
4. There is no need to cast malloc, It returns void *.

9868 35 Light Poster

Hello Every one

Does any One know the format specifier for BYTE. so that it can give me Binary output.

There is no format specifier for binary output, you have to make a code to get the binary output.

9868 35 Light Poster

CAn you tell the exact line where the error is?

9868 35 Light Poster

Could u gv me the website tat can download c programing the notes n the example? Thx^^

Google C programming tutorials and you will find more than a ton.

9868 35 Light Poster

Something like

do {

/* your code here */
} while (condition)

You forgot the semicolon after the while.:icon_smile:

9868 35 Light Poster

Believe me nobody is gonna help you unless you show some progress in your assignment.

9868 35 Light Poster

I need to write a function that traverses a general list and deletes all nodes that are after a node with a negative key.
But I dont know where to start so can I get some help

1. Make a simple linked list by adding several nodes to it.
2. Traverse it using either in,pre or postorder using recursion.
3. Delete the nodes.

9868 35 Light Poster

goto makes the code unreadable and hard to debug. The only place where goto is advisable is coming out of a nested loop.

9868 35 Light Poster

> If f() is called first than, the whole purpose of precedency is lost.
Oh man, learn to read.

f() called first, result stored in temp1 - have we done + or * yet - no.
g() called next, result stored in temp2, have we done + or * yet - no.
h() called last, result is still in a register.
Multiply register with temp2 - woohoo!, we did * first.

Sure, you might be thinking
call g(), result in temp1, call h(), multiply by temp1, store in temp2
Then call f(), add temp2 and store result.

Different - yes
Same result if all the functions are free of side effects - yes
This order is mandated by the standard - nope.
Undefined outcome if any of the functions have overlapping side effects - you bet your ass it's undefined!.

Dont get too excited buddy. It would have been much simpler if you told me that way early. And please be more patient next time you deal with a C learner like me, you bet your ass you're not the only one who knows all this and be cool next time.

9868 35 Light Poster

> according to you which one of the 3 functions will be called first.
No idea, it doesn't matter, I don't care.
That's for any individual compiler writer to decide. It's not in the language spec to define such things.

* happens before +, which in turn happens before =
That's all you have to go on, anything else which happens is up for grabs.

> You mean to say that f() will be called first in f()+g()*h().
Read - MAY BE CALLED FIRST.

If your code depends on it being called first (or last), then your code is broken - no ifs, buts or maybes.

Dont you think there is no chance in hell that f() will be called g() or h(), coz * has higher precedence than +. If f() is called first than, the whole purpose of precedency is lost.

9868 35 Light Poster

> according to you which one of the 3 functions will be called first.
No idea, it doesn't matter, I don't care.
That's for any individual compiler writer to decide. It's not in the language spec to define such things.

* happens before +, which in turn happens before =
That's all you have to go on, anything else which happens is up for grabs.

> You mean to say that f() will be called first in f()+g()*h().
Read - MAY BE CALLED FIRST.

If your code depends on it being called first (or last), then your code is broken - no ifs, buts or maybes.

Dont you think there is no chance of f() getting called first, coz the precedence of * is higher than +, so either of g() or h() will be called first.

9868 35 Light Poster

> In you case f()+g()*h(), g()*h() will be done first coz * has higher precedence than +,
> but which one of the two g() and h() will be called is entirely dependent on the compiler.
Read Dave's link, there is nothing which says that f() won't be called first (or second for that matter).

t1 = f();
t2 = g();
t3 = h();
t4 = t2 * t3;
answer = t1 + t4;

Is just as plausible as any other evaluation.

Precedence defines the order in which intermediate results are combined, but says nothing about the order in which the intermediate results themselves are arrived at.

Throw in some CSE and bits of your overall expression could be all over the place.

Ahem..............You mean to say that f() will be called first in f()+g()*h(). Ok here's another example:
a=f1()*f2()+f3();
according to you which one of the 3 functions will be called first.

9868 35 Light Poster

Going to attend interview in few hours pls
i need some basic questions with answers in C


Dont send links pls sirs i am fresher..

So. What do you want us to do? We dont know what will be asked in the interview? BTW you cant crack an interview by studying a few hours before for it.

Salem commented: Damn straight! +36
9868 35 Light Poster

Compiling the following problem with visual studio 2000 gives the errors:

temp.obj : error LNK2001: unresolved external symbol "void __cdecl ungetch(int)" (?ungetch@@YAXH@Z)

temp.obj : error LNK2001: unresolved external symbol "int __cdecl getch(void)" (?getch@@YAHXZ)

Debug/temp.exe : fatal error LNK1120: 2 unresolved externals

Error executing link.exe.

The code is taken from Dennis Ritchie's "C Programming Language" 's page 97 (2nd Edition).

#include<stdio.h>
#include<ctype.h>

int getch(void);
void ungetch(int);

int getint(int *pn)
{
	int c, sign;
	
	while (isspace(c=getch()));

	if(!isdigit(c) && c != EOF && c != '+' && c != '-')
	{
		ungetch(c);
		return 0;
	}
	
	sign = ( c == '-') ? -1 : 1;
	
	if( c== '+' || c == '-')
		c = getch();
	
	for( *pn = 0; isdigit(c); c = getch())
		*pn = 10 * *pn + (c - '0');
	
	*pn *= sign;

	if (c != EOF) ungetch(c);

	return c;
}

int main()
{
	int *p;

	p = new int[10];

	p[0] = 4;
	p[1] = 2;
	p[2] = 6;
	p[3] = 8;
	p[4] = 2;
	p[5] = 1;
	p[6] = 7;
	p[7] = 1;
	p[8] = 2;
	p[9] = 1;

	int i = getint(p);

	printf("The value is %d", i);
		
	return 0;
}

1. The problem is that you have declared getch and ungetch() but not defined it anywhere, so define it also.
2. You are mixing C++ with C, I think new opeartor is used with C++ but not with C.

9868 35 Light Poster

Agreed that a+b+c is (a+b)+c if left to right associativity is assumed .
Do u mean that associativity rules are applied if an operand competes for two operators of same precedence simultaneously.

Take an example
f() + g() * h()
When I want to evaluate this expression first I will go for function call as it has highest precedence but then why should I not apply the associativity rule because it imposes an order of evaluation of operands. Am I right??

Can someone give an example in which associativity rules are applied for the function call operator ??

Yes, associativity is applied only if you have operators of same precedence in the precedence table.
In you case f()+g()*h(), g()*h() will be done first coz * has higher precedence than +, but which one of the two g() and h() will be called is entirely dependent on the compiler. Take a look at this example.

int a=5,b=6,c,d;
c=a,b;
d=(a,b);
printf("%d\n%d",c,d);

Check the output and make this clear.

9868 35 Light Poster

Hello, simple program here i can't seem to get to work. In a nutshell the program reads characters into an array using getchar and then prints them in a loop, although the numbers printed are not the ones i entered! thanks in advance

#include <stdio.h>

#define MAXSIZE 100 /*max array length*/

int arrlen(int []);

int main()
{
	int c, i = 0;
	int s[MAXSIZE];
	
	while((c=getchar()) != EOF && c != '\n'){ /*while the chars read havn't reached a new line or EOF */
		s[i++] = c; /*Read them into an array*/
		if(c == '\n'){
			s[i++] = c;
			}
		}
	s[i] = '\0'; /* terminate the array */
	
	for(i=0;i<arrlen(s);++i){
		printf("%d\n", s[i]);
		}
	return 0;
}

int arrlen(int array[])
{
	int i;
	
	for(i=0;array[i] != '\0';++i) 
	;
	return i; /*return legnth of the array*/
}

There is a library function strlen() in string.h which returns the length of the string. The only thing you need to do is just change the %d to %c in printf coz you are entering the characters and want teh output of those characters not their ASCII values.

9868 35 Light Poster

If I remove it my program does not compile. That is why I was asking. Was not sure what it was for, but I know it had to be there.

Thanks guys.

1. Looking at your code now, I must tell you that those return 0s were not for main(). You dont have return 0 associated with main anywhere in your code(which should be before the ending brace of main).
2. You can remove them(return 0) without any errors, but else if has to be managed and you can simply put a semicolon at the end of else if to tell it not to do anything.
3. There is also an issue of '\n' in the keyboard buffer with scanf, so you have to modify it as well to make the program completely executable.
4. switch case is advisable in your code.
5. avoid goto.

9868 35 Light Poster

Thanks
I thought it was some kind of error deal.
What do you mean exactly, "It's on main()"

Adding to jephthah's reply, return 0 is optional in C99 standards. So you can remove it.

9868 35 Light Poster

gotoxy is not a standard C function, so you need other library for that.

9868 35 Light Poster

Please check my code, it has no error but there is something wrong.. I am trying to generate unique ten numbers from 0-99. then insert/store the generated number in an array(check[]) because later, after filling the array (check[]) with ten numbers, I am going to use it to another fuction with its ten unique elements. This is a part of my battleship game assignment.

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

int generator ();

char comp [99];
char user [99];
int check [];

void main (){
clrscr ();
generator ();
getch ();
}

int generator () {
int cIndex, i, j , num;
srand((int)time(NULL));

for (i=0; i<=10 ; i++)  {
cIndex = rand()%99+0;

	 for(j=0; j<=9 ; j++)  {
	   if (cIndex!=check[j])  {
	       check[j]=check[cIndex];
	   }
	   else  {
		;;
 	   }

	 }

  }/*ENDFOR*/

printf ("%d",check[cIndex]);

}

1. Never use void main. main returns int like this
int main(void)
{
}
2. What is the size of check[] in your code?
3. If generator() isn't returning anything then it should be void generator().
4.In the else statement what are the two ;; doing?

9868 35 Light Poster

Here is some info about rand function

9868 35 Light Poster

No. According to C standards main should only return 0, nothing else. Keep in mind it's a special function, you can't do things you do with other ones.

9868 35 Light Poster

Hello...

Im a newb to both C programming and DaniWeb ..

the prob is tht i try to compile this program in TurboC3

#include <stdio.h>
#include<Conio.h>

main()
{
printf( "hello" );
getch();
}

when i press " alt+F9 " it says " Warning:: program should return a value" and no errors

When i press " Alt + F5 " I see nothing but a black screen and cursor on it (like in logo) when i have to get Hello....

wht can be the problem...

anything wrong in the program?

plz help me...

regards
yesh

1.CTRL+F9: to see the output
2. main should return int and nothing else
3. C is case sensitive, so Conio.h is wrong.
4. If I'm not wrong, ALT+F5 is used to hold the screen if you're not using getch().
5. Use code-tags to post your code.

9868 35 Light Poster

why C is a not a object oriented program ?

Because C++ is.

MosaicFuneral commented: Wow... -1
9868 35 Light Poster

Your code is full of errors.
1. Check for matching curly braces.
2. main is returning "sum", it should return 0
3. Check for semicolons
4. C is case sensitive. What are ROWSIZE, COLSIZE?

9868 35 Light Poster

Here is a code:

#include<stdio.h>
#include<string.h>
int main(void)
{
char *s1="hello";
char *s2="world";
char *s3;
s3=strcat(s1,s2);
printf("%s",s3);
}

What does strcat returns? Why does this code results in run time error?
And one more question : Are "hello" and "world" terminated with '\0' in case of char pointers? Please describe a bit.

9868 35 Light Poster

Pointer subtraction takes the size of the type into account. If it's a pointer to char, the size is 1 and with 50 chars the result will be 50. If it's a pointer to int, the size is sizeof(int), and with 50 ints the result will be 50 * sizeof(int).

On your system sizeof(int) looks to be 4, and 50 * 4 = 200.

Yeah the sizeof(int) is 4 on my system. But what you are saying is exactly the opposite of what the output is. The output for (char *) is 200 and for (int *) is 50.

9868 35 Light Poster

here is a code

#include<stdio.h>
int main(void)
{
int b[10][5] ;
int (*q)[10][5] = &b ;
printf("%d", (char*)(q+1) -(char*)q);
}

the output it produces is 200 while if I change the typecast to (int *)(q+1)-(int *)q, the output is 50. I know that q is a pointer to the 2D array b. So q+1 is address immediately after the 50 elements but how does the type casting affects the output. Please explain in detail.

9868 35 Light Poster

Here is a code

#include<stdio.h>
int main(void)
{
  
int a;
a=f(10,3.14);
printf("%d",a);
}
int f(int aa,float bb)
{
	return (aa+bb);
}

If I run the code it produces garbage value, but if I declare the prototype of the function before main it produces the correct output as 13. Why is this so coz without the prototype it's assuming returning int, so in effect it shouldn't have any problem?