Friday, July 31, 2009

How do I get the size of a file I opened in C?

I have opened a file (with fopen() ), so, normally, I have a pointer to a file structure. The problem is, I need to know the size of the file I opened. I thought it might be somwere in the structure, the file descriptor, perhaps. But, I have no idea what FILE structure looks like, or what members it has. So, what would be the easiest way for me to find out the size of the file I just opened?





I'm writting in C.


Thank you in advance.

How do I get the size of a file I opened in C?
// open the file


FILE * pFile = fopen("c:\\temp\\test2.txt", "rb");





// seek to the end


fseek(pFile, 0, SEEK_END);





// the current file position tells us how big this file is


int fileSize = ftell(pFile);





// seek back to the beginning so we can start reading it in


fseek(pFile, 0, SEEK_SET);





Calroth's answer of using fstat is correct when using handles returned by open()/close(), but I don't think it works with FILE *.
Reply:There is a function to return the file length.


Under Turbo C++ (DOS version) and Borland C++


filelength(fileno(ifp));


Visual C++


_filelength(fileno(fp));


Recommend that fp is in Binary Mode
Reply:I don't think there is a function to determine the size of a file.


What u can do is, when u have the FILE struct is to get the end position of the last character, which is also the file size!





long lSize;


FILE * pFile;





// open the file


pFile =fopen("somefilename.ext", "r");





fseek (pFile , 0 , SEEK_END); // move the read pointer to end of the file


lSize = ftell (pFile); // get the file position == file size


rewind (pFile); // move back to the front of the file








U might get in trouble if ur file is extremely large.


Then the function ftell will produce the wrong value. (compiler depend)


Maybe u can use


int fgetpos ( FILE * stream, fpos_t * position );
Reply:Hi there!





The system call to use is fstat().





fstat takes two parameters: a pointer to a file structure, and a "stat" structure. You create the "stat" struct, and pass that into fstat too. Then fstat fills it out. Your file size is in "st_size" in the structure.





If you're using Mac OS X or Linux (or another such OS), you can enter "man fstat" at the command line to learn more. Or check your programming documentation. Or check the link I've posted below.





I could give you some code, but I think that should be enough to go on with. Good luck!





Edit: Ugh, sorry, I'm silly. fstat takes a "file descriptor". You turn a "FILE *" into a file descriptor with the fileno() call. Make your call: fstat(fileno(file_in), %26amp;FileInfo)


How do I return an array from a function written in C?

I'm passing in some numbers, creating an array in that function, and then want to return that array.





I am just learning C, still a beginner, so if you could answer with sample code instead of just instructions, I'd really appreciate it! ("you quantize the pointer and pass in microfleems while maintaining the structure" would go right over my head.)

How do I return an array from a function written in C?
Hi.





Because variables allocated instead a function are destroyed when that function returns/ends, you'll need to create %26amp; return a REFERENCE/pointer to the array.





*ptrArray myFunction() {


myDataElement* myPtrArray = malloc(sizeof(myDataElement)+1);


/*


o what you want to the array


*/


return myDataElement;


}





You may need to correct me on the malloc() syntax. It's been awhile.





-Leon
Reply:Try this link


http://www.thescripts.com/forum/thread61...


How to allow unspecified number of parameters in C function?

For example, in C you have the function "printf" which takes a char* string with text, formatters, etc. and then you pass in a comma delimited list of variables for each parameter you provided in the first string. How do you define such a function? How do you make reference to these parameters? I assume there must be some base pointer which can be used to access the various entries?

How to allow unspecified number of parameters in C function?
Use "..."





I don't really get it, but there's some documentation here: http://courses.cs.vt.edu/~cs1704/notes/A...
Reply:Use ellipses in function definition:





void Foo( ... )





then use the following to get arguments:





va_list marker;


int first = va_arg( marker, int );


char* pSecond = va_arg( marker, char* );


...


va_end( marker );


Polymorphism query:In C++ can a method of a derived class be called using the pointer of the base class?

The method is not declared in the base class..


It is only defined in the derived class

Polymorphism query:In C++ can a method of a derived class be called using the pointer of the base class?
Only if you cast the pointer to be a pointer to the derived class. You can use the dynamic_cast operator to do this.





DerivedClass *pDerived = dynamic_cast%26lt;DerivedClass %26gt;(pBase);





pDerived-%26gt;FcnInDerivedClass();
Reply:no you can't.becouase:


class a


{


};


class b:public class a


{


int b;


int getdata()


{


return b;


}


};


void main()


{


a *pa=new a;// it is 0 byte.


b *pb=*(%26amp;pa);


cout%26lt;%26lt;pb-%26gt;getdata(); // getdata try to access unhandled memory


}

elephant ear

Does anyone know how to fix this code in ANSI C?

http://courses.cs.tamu.edu/bart/cpsc206/...





i know that i have to first compile another file before it which already have, but how does the input scanf work? Please help me b/c i'm new to the programming world!





ps. i keep getting the same errors- warning: passing arg 1 of `scanf' from incompatible pointer type and File processing errors. No output

Does anyone know how to fix this code in ANSI C?
haven't used C in a long time but try fixing this line:





printf("Enter a diameter and side separated"


" by a space and followed by ENTER\n");








so it reads:





printf("Enter a diameter and side separated by a space and followed by ENTER\n");
Reply:dude the code is runnig correctly..


gcc filename.c


In strict sense parameters are passed by values only in C. For pass by reference we simulate it. IS this true

While passing by address, we pass the values of pointer variables i.e. addresses??





Also What is the difference between in call by reference and call by address in C. What abt C++??

In strict sense parameters are passed by values only in C. For pass by reference we simulate it. IS this true
You are correct..we pass the values of pointer variables...which in fact contain the address of where the real data is....so technically in C/C++ pointers are always 4-bytes in size despite the pointer type....it is when it is pointed to that you find the "real" type which can be things like char, int, byte, etc...





Call by Address and Call by Reference are synonymous with each other.





C++ has a newer feature over C where you can reference a variable as an "Alias" ... it's a much easier way than playing with pointers.
Reply:u r rite


dude





its the difference


in call by value value is copied to parameter


where as in reference address of the value is copied to parameter that can hold the value of address
Reply:I haven't programmed for a long time, but I remember you can pass by reference in C++. It's just a simple step that creates a substitute and has some very powerful advantages mainly when used with functions and in 'object oriented' programming. It's like giving a variable an 'alias'. It solves some problems that occur when passing by value.





I'm not sure if you can pass by reference in C (I don't think so).
Reply:Actually there is no call by reference concept in c,call by reference is in oops i think there is no diff in between call by ref in c++ and call by address in c


What is the function of the strtok command ? ( in c programming)?

What is the function of the strtok command?


a. finds the number of characters that occur from the beginning of the string.


b. adds the second string the first string.


c. separates the first string by the characters in the second string


d. finds the pointer to the first occurrence of a specific character in the string


e. none of the above

What is the function of the strtok command ? ( in c programming)?
It splits a line into "tokens" that have "delimiters" between the "tokens". The "delimiters" are usually white space and punctuation.
Reply:Hi there





I won't give the answer, but here's the explanation:





The strtok() function returns a pointer to the next "token" in str1, where str2 contains the delimiters that determine the token. strtok() returns NULL if no token is found.





See this url for more information and you can choose your answer.





http://www.cppreference.com/stdstring/st...





Hope this helps


Why doesn't this work in C?

This is in C NOT c++





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;string.h%26gt;





struct city {


char name[50];


double x;


double y;


};


/* array structure for cities */


struct city cities[100];





char line[100];


int main()


{


char test[7] = "Teasdf";


char *test_ptr;


test_ptr = %26amp;test;


cities[0].name[50] = *test_ptr;


printf("test: %s\n", cities[0].name[50]);





}











Get's this compile error:


[Warning] assignment from incompatible pointer type

Why doesn't this work in C?
char test[7] makes the variable "test" a "char *".


Therefore use "test_ptr = test".


Also to copy the string into city name use strncpy().
Reply:which compiler did you use? I compiled it with gcc and had to make some changes. You have several pointer problems...





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;string.h%26gt;





struct city


{


char name[50];


double x;


double y;


};


/* array structure for cities */


struct city cities[100];





char line[100];


int main()


{


char test[7] = "Teasdf";


char *test_ptr;


test_ptr = test;


strcpy(%26amp;(cities[0].name[0]), test_ptr);


printf("test: %s\n", cities[0].name);


}
Reply:this is a virus code you need to get it off your computer now!! just clean your disk and that should do it.


Question related to C++ threads...?

I'm trying to create a simple C++ program that uses fork() to create three processes which work together to calculate the square roots of all integers from 1 - 100. Each thread is supposed to read the int, print out its root, and increment it. My problem is I don't know how to get all three processes to share this integer! I tried a pointer, but that didn't help. What can I do?

Question related to C++ threads...?
When you call fork(), the child process gets a *copy* of the address space, which is separate from the parent's address space. The data stored at an address in one process won't necessarily be the same as the data stored at the same address in another process. So in this case, each process is working on their own copy of value.





What it sounds like you want to do is use threads, which will run in the same process, and have access to the same memory space (and global variables). You can try using pthread_create() if this is what you're trying to do.





If you really want to use fork() and create separate processes, you can use shared memory to pass data back and forth between the processes. Try using shmget() if this is the case.





In either case, don't forget to use some kind of mutual exclusion on your shared resource! (For example, pthread_mutex_lock() in the thread case, or semget() in the process case). Good luck! ^_^
Reply:Well: according to Editing there is Ctrl in which it does work


with your Computer 's Programming %26amp;Design of course


Refer below


Ctrl+X (cut)


Ctrl+C(copy)


Ctrl +V (paste)


also these others can be found too


please refer again from file


Ctrl +N ( new Window Browser)


Ctrl +T (new Tab)


Ctrl +O (open)
Reply:try codeproject.com


they have good thread articles
Reply:I think if you made the shared variable into a buffer you should be able to synchronize the data. Unfortunately there are no good examples of this on the web so I scanned a section of one of my books for you.


http://www.mediafire.com/?ajxgoy5meet


hope it helps
Reply:was a c++ freak once.. dnt knw how i forgot all of it..





gud luck..
Reply:I tried reading your program but it seems incomplete and missing stuff.... i'm guess u need fork() so ok....





but then whats pid_t ? a typedef/?





getpid(); ? some function?

snow of june

What is **pArgv in C++?

I am taking a intermediete programming course studying the C++ programming language and part of or discussion is to say what **pArgv means. I know it is a pointer, but I am not sure what it means and what the two ** means. I have to do some research, but I cannot seem to find out what this means on the internet.

What is **pArgv in C++?
**pArgv is pointer to pointer.


You had not mentioned the type of the variable it points to:





int **p;





will declare pointer to pointer to integer.
Reply:As noted above **pArgv is a pointer to pointers to char.


But more that that it is to pointer to the information that is passed in via command line arguements.





Your program always has a main() of the form:


int main( int argc, char *argv[])





argv[0] is the name of the program that is running.


argv[1]...argv[argc-1] are the tokens from the command line.





If your command line is:





C:\myprogram.exe file1.dat file2.dat





then argc = 3


argv[0] = "myprogram.exe"


argv[1] = "file1.dat"


argv[2] = "file2.dat"





You can see sample code at the Microsoft site linked to below.
Reply:This is actually dereferencing a pointer value through a pointer. (The ** signifies that argv is a pointer to a pointer.)





The argv vector is actually an array of pointers to strings. The array itself (which can be dereferences using [], can also be dereferences like a pointer), which points to a list of pointers.





The first '*' pulls out the address of the string from the argv array, the second '*' dereferences the address of the string.





In some code, you'll see it written as "char **argv", and in others, you'll see "char *argv[]" which can be used interchangeable.





In a nutshell, argv is pointer to an array of pointers.


Question with c++?

hi all,





can any body give me small programme in c++ that store, sort and print list of name using array ...using function ReadList,,SortList,,,PrintList





note:


use referense and pointer argument and parameter

Question with c++?
// here's a start


// all you need to do is implement the three functions :)





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


using namespace std;





void readList(string []);


void sortList(string []);


void printList(string []);





int main(){


  int numEntries;


  cout %26lt;%26lt; "Please enter number of names to read: ";


  cin %26gt;%26gt; numEntries;


  string * theList = new string [numEntries];


  readList(theList);


  sortList(theList);


  printList(theList);


  return EXIT_SUCCESS;


}





void readList(string [] s){


  // your code goes here


}





void sortList(string [] s){


  // your code goes here


}





void printList(string [] s){


  // your code goes here


}


Write a C program to define a structure Student that would contain student name, Marks of 3 subjects?

Write a C program to define a structure Student that would contain student name, Marks of 3 subjects .The program must read 5 student record in an array of structure and display the details of a student who scored highest.(use pointer to structure)

Write a C program to define a structure Student that would contain student name, Marks of 3 subjects?
http://java3.blogspot.com/


http://allinterviewqa.blogspot.com/


http://mcse-mcsd.blogspot.com/
Reply:Homework?


Write a C program to define a structure Student that would contain student name, Marks of 3 subjects?

Write a C program to define a structure Student that would contain student name, Marks of 3 subjects .The program must read 5 student record in an array of structure and display the details of a student who scored highest.(use pointer to structure)

Write a C program to define a structure Student that would contain student name, Marks of 3 subjects?
are you in ap college and is this question was given to you by sameer sir if yes then only i can help you he gave me that assignment two years back
Reply:i never got answers to such question and further more all such questions atleast mine get deleted so good luck in finding an answer to ur question even if u are just asking out of curiosity(not likely)(or because of lack of good teachers) its regarded as doing ur homework or uni assignment for you.
Reply:You are still trying to do this assignment?
Reply:For getting project assignment help there are better websites,e.g. http://getafreelnacer.com/

sweet pea

Frustrating lags while writing C programs?

I use Turbo C++ ver. 3.0 to write C programs. When I open the compiler, instantly it starts to use the CPU to 100% and it shows lags. By lags I mean that if i type lets say the word "include" then it will appear after some time after I have finished typing it. If I move the mouse pointer the displacement will actually appear after a few seconds. This is really very frustrating. I would like to know the reason and remedy of this problem.

Frustrating lags while writing C programs?
From your words I can understand that:


You are having a window of turbo C++ instead of Full screen. Turbo C++ does not require big RAM , so no need to change the RAM.


Try this it should work:


1) On the Title Bar (The top most bar in that turbo C window), right click and choose properties.


2) In the options tab to your right, you will find display options.


3) Click the Full Screen button.


4) The IDE will now be in full screen. In full screen , you will not have those irritating lags





Happy programming





\\Edit


Are you sure?


Using Full screen does not mean clicking on the maximize button. Instead right clicking on the title bar and using properties to change to full screen
Reply:please visit my site


http://www.ra1.infoad.org
Reply:You didn't mention your computer configuration so its hard to help you increase the Ram and close other application if that doesn't help use C++ visual studio ,it will be easier on your machine
Reply:Try not to use any other application while you use TC. Specially playing songs, using net etc.


Cos C=(-49a^2-22)/(Sqrrt(49a^2+25)...

Cos C=(-49a^2-22)/(Sqrrt(49a^2+25))(Sqrrt(49...


Can you simplify this equation?


I think it's possible


If you can't see it, move your pointer over the 3 dots at the end


It's in a/bc form


Show work please!





From Eniram

Cos C=(-49a^2-22)/(Sqrrt(49a^2+25)...
lets say, a= -49a^2-22





b= sqrrt(49a^2+25)





c=sqrrt(49a^2+20)





lets square, a, b and c





a^2 = 2401a^4 + 484+1078a^2





b^2 = 49a^2+25





c^2 = 49a^2 +20





now lets calculate B^2*c^2=





2401a^4+2205a^2+500





hhmmm....... thought I could come up with something and cancel some stuff in the numerator and denominator, but nope.... I'm unable to go further

bottle palm

C programmers help me please?

want help in a C program


in which i have to display tables of numbers upto the no which user enter





but imust use all of these following


1)pointer


2)function


3)recurtion

C programmers help me please?
ok a function is just a way to divide up the code to do something for you. A pointer points to an address in memory where something is stored, and recursion is a process in which an algorithm is repeated.





Ex:





int NumberArray[100]; //makes an array to store up to 100 integers


int HowLarge; //variable for how many numbers are to be in the array





int *GetNumbers() {


cout%26lt;%26lt;"How many numbers are you going to input?"%26lt;%26lt;endl;


cout%26lt;%26lt;"Choice: ";cin%26gt;%26gt;HowLarge;


for(int i=0 ; i%26lt;HowLarge ; i++) { //the recursion part, it gets user input to add any numbers in the array


cout%26lt;%26lt;"Input Number "%26lt;%26lt;i+1;cin%26gt;%26gt;NumbersArray[i];


}


}


//ok pretty easy, gets numbers and puts them in an array.





void ShowArray(int *Array) { //now we will show the array


for(int i=0 ; i%26lt;sizeof(Array)/4 ; i++) { //cycles through the array


cout%26lt;%26lt;"Number "%26lt;%26lt;i+1%26lt;%26lt;" of the Array is: "%26lt;%26lt;Array[i]%26lt;%26lt;endl;


}


}





that should do it. If you have any questions about the code look at the refrence below.
Reply:instead of asking people to do your work for you, post a code sample of what you have done already. that way you learn what you did right and what you did wrong. Having someone write a program for you is a waste.
Reply:I agree with thunder.... if you show me I can help you, I may be a young girl ( roughly 17) but I got the answers. ^_^ so show me the money!


I desperately need help with a C++ program! I need some intelligent advice!?

I'm writing a c++ function to sort through a BST with the purpose of determining its stem of greatest height, solely through the use of recursion, and given that the only variable in the function is a nodal pointer, the only way to pass any instances of information back is to return the desired integral value since this is an "int" type recursive function


I need 2 integers to make it work; i only get to return 1. i'm trying to think of a new way to do it with just 1.





i cannot pass anything down...


the only variable that the function can pass is the nodal pointer


%26amp; thus the only way to "pass" the height is to send it back up


If i was allowed to pass down, yeah, it'd be cake but it won't let me





I had to determine the "height", or the longest stem, the one with the most terms in it, going from the root up.

I desperately need help with a C++ program! I need some intelligent advice!?
I think this should work





int treeheight(tree *t) {


//base case


if((t-%26gt;left == null) %26amp;%26amp; (t-%26gt;right == null))


return 1;


int h1, h2;


if(t-%26gt;left != null) {


h1 = treeheight(t-%26gt;left);


}


if(t-%26gt;right != null) {


h2 = treeheight(t-%26gt;right);


}


if(h1 %26gt; h2) {


return h1 + 1;


}


else {


return h2 + 1;


}





}
Reply:check out http://www.pscode.com - it's the best source code site around. I don't do C++, but I use that site all the time.


C++ hw questions?

i need help on these.





16. The statements following a while condition may never be executed, whereas the statements in a do-while expression will be executed: - 1 point(s)


at least once





at least twice





as many times as the user wishes





never





None of these








17. A pointer may be initialized with - 1 point(s)


the address of an existing object





the value of an integer variable





the value of a floating point variable





all of these





None of these








18. C++ automatically places the ___________ at the end of string literals. - 1 point(s)


Semicolon





Quotation marks





Null terminator





Newline escape sequence





None of the above

C++ hw questions?
16) A


17) D


18) B





Please do your own homework.


Just read the material!
Reply:1.At least once


2.The address of an existing object ( with %26amp; )


3.Null Terminator or "\0"





Well , the answers above should be right . I have a suggestion for you .... Learn your chapter , Understand it , and if you don't understand it , there's always answers.yahoo.com


Do the above 'cos people really don't like answering homework-help questions where the author hasn't even attempted...
Reply:16. at lest once


17. None of these


18. None of the above


C++ question, test review?

The pointer “head” points to the start of a linked list, “p” points to a node of that linked list, “q” points to the node following the node that “p” points to. What is the effect of the following statements?


newNode = new nodeType;


newNode-%26gt;info = 42;


newNode-%26gt;link = q;


head = newNode;


newNode-%26gt;link = head;





a. A node will be inserted at the start of the list.


b. A node will be inserted between p and q.


c. A node will be inserted after q.


d. None of the above, there is an error








Thanks in advance guys

C++ question, test review?
d. 'head' is pointing to the new node, which makes it the defacto start of the list, but the new nodes link should be pointing to the old first node for that to work properly. The above code first points to the 'q' node which is in the list but not ncessarily the start of it, cutting off all the nodes between the old head and q. Then the link is set to point to itself, cutting off the rest of the list.
Reply:a.

magnolia

C PROGRAMMERS!! homework help please...?

Write a function that, given a 2D array, will determine the minimum and maximum


values of the array. Use the following two arrays:


40 35 30 25 20


20 30 40 50 60


45 55 65 75 85


30 35 40 45 50











200 300 400 500 600


1000 245 78 123 85


981 1001 575 99 333








(a) Use pointer notation for accessing any array elements; don’t use subscript nota-


tion. For example, within your function use *(*(a + i) + j) instead of a[i][j].


(b) Your function should be able to handle 2D arrays with any number of rows and 5


columns. Don’t hard-code array dimensions other than what is required to create


the arrays, i.e., don’t use something like this:


int rows = 4;


int cols = 5;





(c) Print the maximum and minimum values from main()





This Program must work in Microsoft Visual Studio.


Thanks!

C PROGRAMMERS!! homework help please...?
oh hush. he's not going to get a job if he can't do it himself.





void f(int** arr)


{


int max = 0;


int min = 10000000;


int cols = 5;


int rows = sizeof(*(arr + 0))/sizeof(*(*(arr+0) + 0));


for(int r = 0; r %26lt; rows; r++)


for(int c = 0; c %26lt; cols; c++)


{


if(*(*(arr+r) + c) %26gt; max)


max = *(*(arr+0) + c);


if(*(*(arr+r) + c) %26lt; min)


min = *(*(arr+r) + c);


}


printf("Max: %i",max);


printf("Min: %i",min);


}
Reply:You just need to use a double array, Simple homework.
Reply:.section .data


data_array:


.long (your data here)





.section .text


.globl _start





_start:


movl $0, %esi


movl $0, %eax





new_max:


movl %eax, %ebx





loop_start:


movl data_array(,%esi,4), %eax


cmpl $0, %eax


je loop_end


incl %esi


cmpl %eax, %ebx


jg new_max


jmp loop_start





loop_end:


movl $1, %eax


int $0x80





#lol


C++ question?

Please tell me in C++ how does return *this; relates to returning a reference in assignment operator overloading





I am confused because this is a pointer to the current object and the return value of the function is ClassName %26amp; which is a reference. so how can ClassName%26amp; be the return type when we are returning using return *this; statement.





sample code:





MyClass%26amp; MyClass::operator=(const MyClass %26amp;rhs) {


... // Do the assignment operation!





return *this; // Return a reference to myself.


}

C++ question?
well a reference is like a pointer whose address you can't set so *this returns a MyClass Object and c++ can automatically make a MyClass reference from an objec.t


C++ Question?

This is part of an exam review that is supposed to help us study, but I do not know how to solve this problem. How do I start, what is the logic behind it?





Write a C++ function with a 1D


integer array as its input parameter, that returns both the largest and the


smallest number in that array. Also show the corresponding function call.


[Hint: You can either a. pass extra variables by reference and return the min, max values by modifying these


variables in the function, or b. pass a pointer to a structure, to the function.]

C++ Question?
Following is the program





#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;


void main()


{


int ar[10],i;


clrscr();


void getminmax(int[]);


cout%26lt;%26lt;"\n Enter the elements";


for(i=1;i%26lt;=5;i++)


{


cin%26gt;%26gt;ar[i];


}


getminmax(ar);





getch();


}





void getminmax(int x[])


{


int i,j,k,t;





for(i=0;i%26lt;=5;i++)


{


for(j=i+1;j%26lt;=5;j++)


{


if(x[i]%26gt;x[j])


{


t=x[i];


x[i]=x[j];


x[j]=t;


}


}


}


cout%26lt;%26lt;"\n Largest Number is"%26lt;%26lt;x[4];


cout%26lt;%26lt;"\n Smallest Number is"%26lt;%26lt;x[0];





}








Don't wait for Ready made things, modify above program according to your needs.


--------------------------------------...





for more programs visit my blog at


http://codesbyshariq.blogspot.com/
Reply:#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;


int max, min;


void funmaxmin(int []);


void main()


{


int ar[10],i;


for(i=0;i%26lt;10;i++)


scanf("%d",%26amp;ar[i]);


funmaxmin(a);


getch();


}


void funmaxmin(int a[])


{


int i;


max= a[0];


min = a[0];


for(i=1;i%26lt;10;i++)


{


if(max%26lt;a[i])


max = a[i];


if(min%26gt;a[i])


min= a[i];


}


printf("Max = %d /n Min = %d",max,min);


}
Reply:#include %26lt;stdio.h%26gt;


int main()


{


int temp[10],i,tempmax,tempmin;


char ok;


tempmax=0;


tempmin=999999999;


for (i=0;i%26lt;=9;i++)


{


printf("Enter number%d: ",i);


scanf_s("%d",%26amp;temp[i]);


if (temp[i]%26lt;=tempmin) tempmin=temp[i];


if (temp[i]=%26gt;tempmax) tempmax=temp[i];


}


printf("Min:%d\n", tempmin);


printf("Max:%d\n", tempmax);


printf("Is it ok?(press Y to exit");


scanf_s("%s",%26amp;ok);


if (ok=='Y' || ok=='y') return 0;
Reply:the answers 3.3 best of luck





xxxxxxx


Please give me short note of my C++ program...?

Problems are taken from C++ Primer book





-Ensure you can complete prior to accepting and emailing me.





-If you do not provide your price to do this I will not respond…





-I require this completed in 1 week.





Exercise 13.3: Assuming Point is a class type with a public copy constructor, iden¬tify each use of the copy constructor in this program fragment:


Point global;


Point foo_bar(Point arg)


{


Point local = arg;


Point *heap = new Point(global);


*heap = local;


Point pa[ 4 ] = { local, *heap };


return *heap;





______________________________________...





Exercise 13.10: Define an Employee class that contains the employee's name and a unique employee identifier. Give the class a default constructor and a constructor that takes a string representing the employee's name. If the class needs a copy construc¬tor or assignment operator, implement those functions as well.





______________________________________...








Among the fundamental operations a pointer supports are dereference and arrow. We can give our class these operations as follows:


class ScreenPtr { public:


// constructor and copy control members as before


Screen %26amp;operator*() { return *ptr-%26gt;sp; }


Screen *operator-%26gt;() { return ptr-%26gt;sp; }


const Screen %26amp;operator*() const { return *ptr-%26gt;sp; } const Screen *operator-%26gt;() const { return ptr-%26gt;sp; } private:


ScrPtr *ptr; // points to use-counted ScrPtrclass








Exercise 14.20: In our sketch for the ScreenPtr class, we declared but did not define the assignment operator. Implement the ScreenPtr assignment operator.





______________________________________...





Exercise 14.21: Define a class that holds a pointer to a ScreenPtr. Define the over¬loaded arrow operator for that class.


______________________________________...








Exercise 15.4: A library has different kinds of materials that it lends out—books, CDs, DVDs, and so forth. Each of the different kinds of lending material has different check-in, check-out, and overdue rules. The following class defines a base class that we might use for this application. Identify which functions are likely to be defined as virtual and which, if any, are likely to be common among all lending materials. (Note: we assume that LibMember is a class representing a customer of the library, and Date is a class representing a calendar day of a particular year.)


class Library { public:


bool check_out(const LibMemberk);


bool check_in (const LibMember%26amp;);


bool is_late(const Date%26amp; today);


double apply_fine();


ostream%26amp; print(ostream%26amp; = cout);


Date due_date() const;


Date date_borrowed() const;


string title 0 const;


const LibMember%26amp; member() const;





______________________________________...








Exercise 15.8: Given the following classes, explain each print function:


struct base {


string name () { return basenatne; }


virtual void print(ostream %26amp;os) { os « basename; } private:


string basename;


};


struct derived {


void printO { print (ostream %26amp;os) ; os « " " « mem; } private:


int mem;


};





If there is a problem in this code, how would you fix it?





______________________________________...








Exercise 15.13: Given the following classes, list all the ways a member function in Cl might access the static members of ConcreteBase. List all the ways an object of type C2 might access those members.


struct ConcreteBase {


static std::size_t object_count(); protected:


static std::size_t obj_count;


};


struct Cl : public ConcreteBase


{ /* . . .*/};


struct C2 : public ConcreteBase


{ /* ...*/};





______________________________________...





Exercise 15.25: Assume Derived inherits from Base and that Base defines each of the following functions as virtual. Assuming Derived intends to define its own ver¬sion of the virtual, determine which declarations in Derived are in error and specify what's wrong.


(a)Base* Base::copy(Base*);


Base* Derived::copy(Derived*);


(b)Base* Base::copy(Base*) ;


Derived* Derived::copy(Base*) ;


(c)ostreamk Base::print(int, ostream%26amp;=cout);


ostream%26amp; Derived::print(int, ostream%26amp;);


(d)void Base::eval() const;


void Derived::eval();

Please give me short note of my C++ program...?
This kind of stuff, where you pay for someone who codes for you would be best accomplished at http://www.rentacoder.com or http://www.guru.com
Reply:And that is a fact since it goes against community guidelines and rules and will be *REPORTED*.
Reply:looks good to me

forsythia

Accessing private class variables C++?

When you have private class variables in C++:





When accessing these variables from within a class method, why is it this-%26gt;variable, not this.variable like in Java. Also when accessing a pointer is it still this-%26gt;pointer?

Accessing private class variables C++?
Because "this" is defined as a pointer, and to access members of a pointer, you use "-%26gt;". Also, you do not have to use the "this" pointer to access member variables from a member function in a class. There are some instances like in someFunc() below where you may need to specify which variable to use with the same name, or if you want to make it perfectly clear that you are accessing a member variable.





class A


{


public:


A(int zzz)


{


z = zzz;


}





void someFunc(int z)


{


this-%26gt;z = z;


}





void someFunc2(int zz)


{


z = zz;


}





private:


int z;


}


Why does C++ have a string class when there is already char * (a pointer to type character)?

A string is much more easier to work with than the char * due to the following reasons:


1. You have strict bounds checking in strings; char * doesn't have that.


2. If you need to equate two strings, you can just use the = symbol, not have to call the strcpy function everytime.


3. you can check for equality in an if condition ie u can use == to check if two strings are equal.


4. You can access individual characters by using the .at().


5. You needn't call strlen to check the length. all that need to be called is stringvariable.size().





There are a lot other advantages of using string class too. Ultimately, the string class scores on the ease of use. The char * scores on the raw power that it provides. You can use either depending upon your requirement and the time you are ready to devote to coding.

Why does C++ have a string class when there is already char * (a pointer to type character)?
Char is a single entity.......'a' , '1' etc.





But if u have a collection of characters together....."Bombay","computers"......


That is a string.


the space occupied is more 4 strings whereas character utilises only one byte.





Also way of use 4 chars and strs are different.String handling has a very huge application.However ,it should be noted that a string is an array of characters.


And use is so extensive that use of pointers can be sometimes tedious for the use of strings and is not always convenient and so we deal with string class independently though pointer can be used too.
Reply:char* strings are known as C strings. The usage of C strings is considerably more complex, not least because you have to be aware of memory issues.





With C++ strings for example, you can concatenate strings or place new strings in a string variable with little thought for the underlying memory handling. With char* strings, you better be aware of issues such as null-character termination, having enough buffer space when concatenating, and so on.





In short, C++ strings is a level or two above C strings in abstraction.


Simple error in C; printf function.?

This is probably extremely simple and easy, but I can't figure it out, because I usually program in C++. I am getting this error when compiling:





[Warning] passing arg 1 of `printf' makes pointer from integer without a cast





This is my code I use when I get this error, in my function that prints variables.





void printDate(char date[])


{





int n;


for (n = 4; n %26lt; 6; n++)


{


printf(date[n]);


}


printf("/");


int m;


for (m = 6; m %26lt; 8; m++)


{


printf(date[m]);


}


printf("/");


int i;


for (i = 0; i %26lt; 4; i++)


{


printf(date[i]);


}


printf(" at ");


int z;


for (z = 8; z %26lt; 12; z++)


{





printf(date[z]);


}


}














I have no idea why it's screwing up, but if anyone could help me I'd greatly appreciate it :)

Simple error in C; printf function.?
you need to use something like


printf("%c", date[j])


the %c means a variable of type character


i dont know if this is the exact way but its definately he right structure
Reply:the error sounds like you're passing your date, not the address of the date. Without seeing how you call it, its hard to say.
Reply:For printf()





you need the formatted data and then the arguments








Found something to help you:


http://www.cplusplus.com/reference/clibr...
Reply:printf() definition is


printf(char *, ...)


You are trying to call it as


printf(char) which causes this error


I have updated the code so it uses putchar() to output a character.





void printDate(char date[])


{





int n;


for (n = 4; n %26lt; 6; n++)


{


putchar(date[n]);


}


printf("/");


int m;


for (m = 6; m %26lt; 8; m++)


{


putchar(date[m]);


}


printf("/");


int i;


for (i = 0; i %26lt; 4; i++)


{


putchar(date[i]);


}


printf(" at ");


int z;


for (z = 8; z %26lt; 12; z++)


{


putchar(date[z]);


}


}


The letter for today children, is C. What religious word, phrase or story...?

can you come up with that begins with the letter C?





I shall start: Communion Cookie (Whoo! That there would've been a 20-pointer if I hadn't said it myself!)

The letter for today children, is C. What religious word, phrase or story...?
Crucified christ concept currently complete crap
Reply:Cet and Cuar-- two Celtic Gods.
Reply:CRT... Just lay your hand on the screen!
Reply:Chewy chunky chocolate chip Cookie, the superlatives are endless.
Reply:Cat Crap Catechism
Reply:Cats For Christ!
Reply:Capricorn!
Reply:I can never get these trick questions. *sweat drops*
Reply:can o' fanaticism











Santa is returning soon, are you prepared?!
Reply:Catholic crucifix


cranky Christian


catechism craze
Reply:Calafornication.
Reply:chakra
Reply:cernunos cut cheese
Reply:Copacetic cross.





Thrice Baked- I apologize if the Adam and Steve thing offended you on my other answer. I realize that some people do not agree with my views on gay marriage, although I believe that you and I both have a right to express our opinions. However, I do think that it was unfair of you to accuse me of being a bigot. I have nothing against homosexuals. Next time, please think before you libel people.





EDIT- Yes. I feel a similarly, except I believe that no matter what people believe, we should treat each other with respect, and all the atheists can quit making fun of other people's beliefs.
Reply:Compassionate Christianity





(which means to treat one another with kindness even when the other person does not)

jasmine

I am new in c languvage then i wanted great tutorial and mainly?

i am new in c languvage then i wanted great tutorial and mainly


about files what is file pointer what is uses of files


so help me particular site..........


i saw more site but not cleary

I am new in c languvage then i wanted great tutorial and mainly?
There are several free tutorials available on the internet. Each one seems to offer a slightly approach to learning C. But the one thing in common is you're learning a new language... like an English speaker learning French or German. It's difficult.





http://www.cs.sfu.ca/CC/401/zzhang/ctuto...





http://www.coronadoenterprises.com/tutor...





The tutorials above might get you in the right direction.





wwbgd


Some Interview Questions that I need solution in C language...?

1. Given 2 files, f1 and f2 with thousands of name each. Find the common names in the two files. Extend this to 3 files.





2. Algorithm to count most user viewed pages.





3. Code to find dot and cross product





4. Write a function that accepts a function pointer and check the procId of the calling process. Check if the process was alive at a specific interval. If yes, then invoke the function (pointed to by the function pointer) else return. Write another function that would take a request from the process to stop the first function





5. You have 50000 html files, some of which contain phone numbers. How would you create a list of all the files which contain phone numbers?





6. Write C code for 'tr' program.


C:\%26gt; tr abc xyz %26lt;file name%26gt;


replaces all occurances of a by x, b by y and c by z in %26lt;file name%26gt;





7. Given a sentence, find if a specific word occurs in it.





8. Write the data structure for jigsaw puzzle. Assume that there is some method which can tell if 2 pieces fit tog

Some Interview Questions that I need solution in C language...?
Dude, you can't get a job by asking solution to problems. Atleast try solving them and then you can ask your doubts one at a time.


No one will solve all these problems from scratch. You need to do some work at your end.


Reading integers from FILE in C?

I have a file that has integers on one line diveded by one space and nothing else.


For ex:


6 23 -2 45 -11





I have to do more things with these numbers, find the sequence with the maximum sum and others. But that's not the problem, I can do that. The problem is reading these numbers as integers and not as strings. I've tried reading them as strings and then using atoi() but I get a warning about atoi: "passing arg 1 of atoi makes pointer from integer without cast" - something like that.


My declaration is char b[1000]; char c. c is the variable in which I read characters from the file with getc(). If I declare them as char *b, *c, I don't get any more warning for atoi() but reading from the file doesn't work anymore.


Any suggestions?

Reading integers from FILE in C?
Have you tried looping (until end-of-line or EOF) using fscanf? This function is used like fprintf/printf. So,


FILE *filePointer;


int myInt;





/* Open the filePointer...blah blah blah */





/* Read an integer into myInt */


fscanf(filePointer, "%d", %26amp;myInt);





No atoi conversion is needed in this case...it's already an int. The getc function will only retrieve one character at a time. For example, 23 would be read as 2 and then 3. Alternatively, you could read like this, entering each character into a char array until you hit a space and then, after adding a null-string char ("\0") send this into atoi.


Writing a C++ program to display letters backwards?

I'm going through a C++ book before I return to school in the fall and have come across a problem that is giving me issues. Basically, I am supposed to initialize a pointer-based string variable to all 26-letters in the alphabet in upper case. So it should be "ABCDEFGHIJKLMNOPQRSTUWXYZ". Then I am supposed to declare a character array based string variable to store up to 26 characters to be entered from the user. I should then print what the user entered, and then print the upper case alphabet backwards, and then what the user entered backwards. I can only use arrays and pointer-based arrays, as that's all I know right now.





Can someone give me a hand with this? Should output:





The first string is:


"ABCDEFGHIJKLMNOPQRSTUWXYZ"


Enter the second string up to 26 characters:


abcdefghijklmno


You have entered:


"abcdefghijklmnopqrstuvwxyz"


The first alphabet backwards is as follows :


ZYXWUTSRQPONMLKJIHGFEDCBA





The second alphabet backwards is as follows :


zyxwvutsrqponmlkjihgfedcba





Thanks!

Writing a C++ program to display letters backwards?
As an example of what mapaghimagsik is advising, I provide the following example. Doesn't get too much sweeter than this but sadly so few people seem to make it through all the C junk while learning C++ that they never get to a lot of the good stuff.





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main()


{


string s("abcdefghijklmnopqrstuvwxyz");





string::reverse_iterator rit = s.rbegin();





while (rit != s.rend())


{


cout %26lt;%26lt; *rit++;


}





cout %26lt;%26lt; endl;


}
Reply:Use a for loop to print a string backwards. Initialize it to the length of the string and terminate on 0.





The alphabet is a literal string.
Reply:check out: http://www.planet-source-code.com
Reply:You can get a reverse_iterator on a string. Use that to move backwards through the arrays.
Reply:Ascii numbers for the alphabets are starting from 65-90(A-Z)


then use the ascii numbers to print the alphabets in the reverse order, if ur program is only with alphabets. If u want to reverse the string take the string length and read from last to first number to print the alphabets in the reverse order.

crab apple

In C++, what is the meaning of char * ? How to recall this pointer ? Any simple example..?

i'm still learning myself but try this





http://www.cplusplus.com/doc/tutorial/po...

In C++, what is the meaning of char * ? How to recall this pointer ? Any simple example..?
In computer memory, each byte has an address and a value.





Given the line


char myVar = 'D';





The compiler puts the value 'D' in some memory address.





In C/C++ you can actually get that address with the %26amp; operator.





char * myValAddress = %26amp;myVal.





Think of the %26amp; operator as the "the address at" operator.





when you see


char * myValAddress = %26amp;myVal


read it in your head as


myValAddress equals "the address at" which myVal is stored.





Now myValAddress is a "pointer" to the location where myVal is stored.





You can now either change or get the value with the variable name myVal, or change the value by "dereferencing" the address pointer with the * operator.





char newVal = myVal;


char newVal = *myValAddress;








think of the * operator as "the value pointed to by"





when you see


*myValAddress = 'F';


read it in your head as


"the value pointed to by" myValAddress equals 'F';





Any quest, email me at redflats@yahoo.com
Reply:A string.


In c++, what is the difference between a character array (or a pointer to one) and a literal string?

In c and in c++ a character array is an array of bytes, normally containing ASCII values. A literal string is an sequence of ASCII characters terminated with a null ('\0'). Example:





char array[9] = { 'a','b','c','d','e','f','g','h','i','j' };


char str[] = "abcdefghij";


char *ptr = "abcdefghij";





array[] will contain the ASCII string 'abcdefghij' without a null string terminator: example array[] contains:





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


a b c d e f g h i j





str[] contains:


[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]


a b c d e f g h i j '\0'





ptr will contain the address of the first byte of the literal string "abcdefghij"; ptr+10 will be the address of the null terminator.

In c++, what is the difference between a character array (or a pointer to one) and a literal string?
there is some difference in memory assignment and accesing if you put alignment larger than 1. Say compiler option alignment is 8, then compile will assign 8 byte space for one char. For string, it assignes memory space for each char either one byte (ANSI) or two bytes (unicode).





Therefore, accessing those char in array will be more complicated


Questions for C Language Excepts Only?

Plz Can anybody answer below questions





-%26gt;What is the most efficient way to count the number of bits which are set in a value?


-%26gt;How can I convert integers to binary or hexadecimal?


-%26gt;How can I call a function, given its name as a string?


-%26gt;How do I access command-line arguments?


-%26gt;How can I return multiple values from a function?


-%26gt;How can I invoke another program from within a C program?


-%26gt;How can I access memory located at a certain address?


-%26gt;How can I allocate arrays or structures bigger than 64K?


-%26gt;How can I find out how much memory is available?


-%26gt;How can I read a directory in a C program?


-%26gt;How can I increase the allowable number of simultaneously open files?


-%26gt;What's wrong with the call "fopen("c:\newdir\file.dat", "r")"?


1. Explain working of printf.


2. Explain "passing by value", "passing by pointer" and "passing by reference"


3. Have you heard of "mutable" keyword?


4. Talk sometiming about profiling?


5. What is Memory Alignment?


6. Why

Questions for C Language Excepts Only?
-%26gt;What is the most efficient way to count the number of bits which are set in a value?





Lookup table





-%26gt;How can I convert integers to binary or hexadecimal?





What do you mean? As a string? Just use the printf modifiers.





-%26gt;How can I call a function, given its name as a string?





Use a map of pointers to functions





-%26gt;How do I access command-line arguments?





main( int argc, char * args[] )


argc has the arguments count, args has argc arguments - the command line argsuments





-%26gt;How can I return multiple values from a function?





Via pointers in the arguments





-%26gt;How can I invoke another program from within a C program?





You should not. But system() gets the job done.





-%26gt;How can I access memory located at a certain address?





Use a pointer, set pointer to that certain address





-%26gt;How can I allocate arrays or structures bigger than 64K?





WTF? Are you in 16bit real mode under dos or what? Read the system docs.





-%26gt;How can I find out how much memory is available?





Use OS calls ( see your OS documentation )





-%26gt;How can I read a directory in a C program?





What do you mean by read? See OS docs.





-%26gt;How can I increase the allowable number of simultaneously open files?





See OS docs





-%26gt;What's wrong with the call "fopen("c:\newdir\file.dat", "r")"?





Not portable?


Handle not saved?


Folder not available?





Even if there is a problem, it is specific to your code. So I cannot help.





1. Explain working of printf.





See http://www.cplusplus.com/reference/clibr...





2. Explain "passing by value", "passing by pointer" and "passing by reference"





C has no passing by reference. In c++, see http://www.cplusplus.com/doc/tutorial/fu... - similar in C except for reference part





3. Have you heard of "mutable" keyword?





Yes. But it is C++, not C. http://www.cppreference.com/keywords/mut...





4. Talk sometiming about profiling?





It evaluates how long each of the functions run in a program. Used for optimizations/debugging.





5. What is Memory Alignment?





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





6. Why





Why What?


C:\WINDOWS\system32\shutdown.e... -s -t 600 -c "Trojan Detected"?

most of my shortcut change into C:\WINDOWS\system32\shutdown.exe -s -t 600 -c "Trojan Detected" then after restart cmd run itself and type many start explorer command then after a while my pointer can move by it self can any1 help me?? i already format my laptop but its nt work

C:\WINDOWS\system32\shutdown.e... -s -t 600 -c "Trojan Detected"?
Before you rush out and install a lot of free software, be SURE to check out how well it works. Some people think that because it's free and supported by "the community" it's somehow pure and perfect. Many (too many) free programs are not that pure or that effective. See the unbiased reviews in PCWorld. http://www.pcworld.com/article/124475-1/...


Note that AVG is at the bottom of the list. Using ineffective virus protection is worse than none at all... it gives you a false sense of security.
Reply:Step 1: Make sure that you have an up to date antivirus program. If you don't, install AVG.


Step 2: Visit the Google Pack website, and use it to download Spyware Doctor.


Step 3: Download and install ThreatFire.


Step 4: Make sure to use Mozilla's Firefox from here on out. Also, install the Adblock Plus add-on for it.


Step 5: Make sure that you have a firewall program on your computer. If you don't, install Comodo.
Reply:i am not the real chris b
Reply:Clearly you are indeed NOT properly formatting your computer if this is continuing to be present. If you are merely "reinstalling" or you are using a "recovery cd" then you are in fact NOT fomatting.





Insert your windows xp cd into the cdrom drive and boot to it.. choose the FORMAT option before you reinstall the operating system... then when the computer reboots.. before you start installing crap.. get your butt to bestbuy and INVEST in a proper security suite from a reliable vendor like McAfee Total Protection that includes antivirus, firewall, antispyware,etc.. and then ensure it is properly configured and completely up to date before you reboot and scan





After that force manual windows updates and reboot as necessary until your computer is completely current and reboot again and repeat until complete.





After you've secure the computer in this manner you can then begin to reinstall programs and files.. and hope that they are not infected.





Good Luck

strawberry

C ...string prototype declaration problems..... it's very very urgent...?

if u see the help of turbo c....u will find there the declaration of strcat..(string concatenation)....


char *strcat(char *target,char *src);





but whenever we use this fucntion we write like this...





strcat(target,source);


where target n source both are the strings..





now my question is that....if the declaration returns chararcter pointer then how we can write...strcat(target,src); coz...in this function calling ,no character or no character pointer is stored...any where.so plz explain me this...as soon as possible for u...i really need it.

C ...string prototype declaration problems..... it's very very urgent...?
char *strcat( char *strDest, const char *strSource );


It will copy contents of strSource to the location pointed by strDest.


And returns the pointer strDest which is not required.


The location strDest should be allocated with enough space for the strSource.


Eg:


char string[80];


strcpy( string, "Hello world from " );


Dont worry about the return char* which is the same string.





Both should be null terminated and stdDest should be having enough space to hold strSource,otherwise it will result in overwritting data and crash your program at some time.
Reply:actually in C, strings are just array of characters.





Hence u use, char a[10] to store a string of 9 chars.





a[10] has 10 chars, starting from a[0] to a[8] and a[9] is the null char.





I think u know all these stuff.


Lets get to this problem.





this array will store data in memory in order. for eg: char a[]="gopi" will be stored in memory as g o p i '\0'





hence if the address of the first char is known, the rest of the data can be read easily by increment.





like char *p;


p=%26amp;a[0];


for(i=0;*p!='\0';p++)


{printf("%c",*p);}


and for such string functions, usually the functions, they accept the address of the first char and are able to read the entire string.





for eg. ur scanf();


u do not use '%26amp;' symbol for %s in scanf. scanf("%s",a); will display the str. Notice that u dont use the '%26amp;' symbol.





a[0] is similar to a in such str functions.





Understand?


If u have any prob. mail me.
Reply:when u use strcat(target,source)


then through strcat function u are just passing the base address (through char pointers)of both the arrays of string to the strcat function.


this function concatinates two string and returns a char pointer which holda the base address of the concatinated string. the null character of first string is replaced by the very first character of the second string.......


it is the simple working dude


Why does my Turbo C compiler produce a fatal error whenever I use a pointer?

Need help.

Why does my Turbo C compiler produce a fatal error whenever I use a pointer?
change the memory module to huge while compile ur code. try simple codes like





int main()


{


int *p;


p = (int *) malloc (sizeof(int));


scanf("%d", %26amp;p);


printf("%d",*p);


}





u can find differ, i think...
Reply:U might be using the pointer wrongly.... post a sample code here..


I have a question about c ++?

i am reading my book but it does not give examples at all...


its a c++ book...


write code so i can study it for best answer. Two questions








1. Write the statement, which declares a pointer to an integer data-type. Name the pointer 'd_address'.





(what the hell is a pointer) how?





2. Write a function definition header named 'return_address' which returns a pointer to a dynamically created array of integers. The function should receive an integer in a variable named 'numbers'.


Note: do not write the code for the function block, only the header!


(no idea)

I have a question about c ++?
I will referr you to some sources that may help.


I hated C++ and have done a brain dump on that entire language. ;o)
Reply:pointer holds the memory location adress of the variable.





1:





int * d_address;


// The star declares the variable as a pointer





2:


int* return_address( int numbers )


//int* is the type of a pointer on int
Reply:A pointer holds the address in memory of the location of the variable. So in #1:


int * d_address; // The star declares the variable as a pointer





#2. int return_address( int numbers )





The first int is the type that gets returned by the function. The int numbers is the passed in variable.


As it is a good practice that C# brought back the concept of GOTO statement and Pointer? If your answer is?

It may be down to taste but I think GOTO's should be left back in BASIC where they belong. :) Pointers are the bread and butter of c++ programming and a completely different animal.





C# is managed code and therefore any use of pointers is restricted to areas of code marked UNSAFE. Although not bad practice all use of unsafe code should be done with caution.

As it is a good practice that C# brought back the concept of GOTO statement and Pointer? If your answer is?
They are totally different. Pointers stores and adress of any data. Goto is related with process order of your code. In C# you dont need GOTO but if u want to make a loop or change the direction of the code u can use "break;" "continue;" or call functions.
Reply:Huh?





Pointers and GOTO statements are totally separate concepts.





GOTO statements usually result in lazy programming. In good OO design, there's no need for





In my opinion.

kudzu

Passing strings in C?

I'm pretty new to C and need help with strings. I also have no idea about the differences between C and C++, so please only help with info on C and not C++ or C#.





If I created a string in a function and want to pass it as a return value for the function to use in other functions, how can I do this without loosing the string when the function ends?





I know that when a function ends, everything that is local to it gets, for a better word, destroyed. If you can only return/pass the pointer to the string created in the function, when the function ends, won't the actual string be destroyed/reallocated and the pointer be essentially useless? How can I return the actual string/keep it for use in other functions?

Passing strings in C?
ok.... you have the basics right. so this is what you need to do





char * foo() {


int str_size = 6; //example size.


char * x = (char *) malloc(sizeof(char)*str_size);


sprintf(x, "%s", "hello");


return x;


}





the malloc is allocation memory from the heap. this will ensure that even when you exit the foo method, the location is not reclaimed. And you return the address to the same.


So you should be fine.
Reply:but don't forget to free() the pointer when you don't need it anymore, otherwise you will have a memory leak.


C shaped hand?

does anyone know what it means when people pose for a pic and they hold up their hand kinda in a c shape...?





%26gt;its like there doin the 'okay' hand signal -but their pointer and thumb have a space...





and it aint aggressive or anything so. . . . . ?

C shaped hand?
two c shaped hands make a heart....try it





x


In C, FALSE is represented by any expression with the value of 0. Choose the valid expression below ...?

to represent FALSE??????











a. the NULL pointer


b. A floating expression having the value of 0.0


c. The null character '\0'


d. All of the above

In C, FALSE is represented by any expression with the value of 0. Choose the valid expression below ...?
D, all of them will evaluate to false
Reply:U not able to read your notes to fo your own homework ?
Reply:b








a null pointer points to no adress


a null char is a char only


so answer is b


Passing Array of Objects in a function [C++]?

I'm trying to pass an array of pointer objects into a function





My base class is an Account. The derived classes are checking, savings, and credit.





code snippet





Account* a[100]; // array of pointer objects





void buildAccounts( Account%26amp; a ); // function call


{


switch( type )


case: ('c')


a[i] = new Checking;


case: ('s')


a[i] = new Saving;


case: ('r')


a[i] = new Credit;


}





I understand that I can not pass the array like this in the function... Anyone know the workaround?

Passing Array of Objects in a function [C++]?
First of all, anytime you pass an array to any function, the syntax is as follows:





typeOfElementsInArray arrayName[ ]





So, let's apply this to your function:





void buildAccounts(Account* a[ ])


{


}





That's it. Don't make it harder than it really is. Another thing, remove the semicolon after the header of your function and the comment you have there "// function call" is incorrect because this is not a function call it's a function definition.





Now, where is "type" stored and how are you retrieving it? The thing is, you have not created your objects yet!! What you can do is something like the following (assuming the array contains a single person's accounts):





a[0] = new Checking;


a[1] = new Saving;


a[2] = new Credit;





We actually need to understand this better. Is this array of accounts just for a particular customer or it contains everyone's accounts? Please, try to clarify what you are doing with the array and the nature of your program so I can help you better.
Reply:Because buildAccounts doesn't know that a is really an array, you can't use subscript notation to assign to it. I think you have to use pointer notation (a + i).
Reply:void myfunction( - ) {


    \\stuff is here


    Account** a = new Account*[100];


    \\stuff is here


\\I have assumed type is an array of all the account types


\\You can adjust accordingly


    buildAccounts( a, type );


    \\stuff is here


}





void buildAccounts( Account** a, char* type) {


    for(int i=0; i%26lt;100; i++) {


        switch( type[i] ) {


        case 'c':


            a[i] = new -;


            break;


        case 's':


            a[i] = new -;


            break;


        case 'r':


            a[i] = new -;


            break;


        }


    }


}


\\Adjust this function as required
Reply:Hi Whiteshooze,


I think you can find your answer here:





http://www.onlinehowto.net/Tutorials/C++...

garland flower

C code question regarding malloc() and free().....?

file ----%26gt;input.h (contents of input.h)


float * datain();


file ----%26gt;input.c(contents of input.c)


#include %26lt;malloc.h%26gt;


//.....other includes


float *datain()


{


float *data;


//routine to get data........


return(data);


free (data) ///????????


}





assuming I have a main.c function in the same project which calls datain()...is it legal operation to free the pointer after returning the pointer to the main function? even though I need to do some thing to the returned data?





file----------%26gt;main.c





#include %26lt;malloc.h%26gt; ....//other includes


#include "input.h"





void main ()


{


float *getdata;


getdata = datain();





// .....do something to get data;





}








Thanks in advance

C code question regarding malloc() and free().....?
statements after return statement are not executed.


so basically, your function does not execute the line


%26gt; free(data)





instead of that, you could define a structure and two functions,





typedef struct {


float * data;


int valid;


} datastruct;





datastruct get_data(){


float *tmp;


// malloc(tmp)





// copy data to memory pointed by tmp





datastruct result = {tmp, 1};


}





float free_data(datastruct *pdata){


if (pdata -%26gt; valid){


pdata -%26gt; valid = 0;


free (pdata -%26gt; data);


}


}





==================





and inside your main function:





void main(){


datastruct data;


data = get_data();





// do smth to data





free_data(%26amp;data);


}
Reply:you're right, the struct is not really needed. Report It

Reply:Actually in C different memory space will be alloted for the functions so whenever u pass a data the value will be passed but when it is a pointer it only passes the address of the pointer so if u pass a pointer from one function to another the address of the pointer will be passed.





If u want to free a pointer the u need to pass the data value instead of using address of the pointer


ie instead of return(data); use return(*data); It passes the data value so when u free the location u dont have any problem





If u free the pointer only the pointer will be freed ie if u free data then it will be deleted (the location having the address of original data )as u have already passed the address if u free there is no problem .if u free first the original address of data will be lost thus the data becomes inaccessible .








I think i have atleast solved some of your problems
Reply:I really didn't use C before ... but i know the pointers concept.





I think there's no problem if u make the pointer "data" free after returning the data


even if u need to do things to the returned data in the main.





----


*u've pointer "data" in dataIn() and pointer "getData" in the main,


*what is really done here is that u recieved some DATA


*the DATA now is in the memory with address "150" for example


*u put the address "150" in the pointer "data"


*u returned the pointer value to the pointer "getData"


*then "getData" now contains the address "150"





i don't know the function "free" but,





when u free(data):





-if that means u make the pointer itself free and not points any DATA, so u still have the pointer "getData" points to the same data.





-if it means u'll delete the actual DATA pointed by the pointer "data", then that's wrong





but it seems like the 1st meaning is right


----------------


another thing :


as i said b4, i didn't use C before ... but in Java, the statements after "return" aren't reachable as the function ends at the word "return", i don't know if it's the same thing in C or not
Reply:[747] cmalloc: cat main1.c


#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;





float *dataIn( void )


{


float *dataPtr = malloc( sizeof(float) );





*dataPtr = 1.2345;


return dataPtr;


}





int main( int argc, char* argv[] )


{


float *myDataPtr = dataIn();





printf( "myDataPtr: %p\n", myDataPtr );


printf( "*myDataPtr: %f\n", *myDataPtr );





free( myDataPtr );


return 0;


}


[748] cmalloc: gcc -Wall main1.c


[749] cmalloc:


[749] cmalloc: ./a.out


myDataPtr: 0x3000f0


*myDataPtr: 1.234500








The dataIn() function allocates the memory, fills it in, and returns a pointer to the data. The main() function gets a pointer to the data from the dataIn() function. The ownership of the allocated memory passes from the dataIn() function to main(). The main() does whatever it wants with the data and then frees the memory.





You must NOT free the memory until all the program is completely done using the data stored within the memory.


Write a C function?

Write a C function show() that has three arguments, the first is a pointer to a two dimensional dynamic array, the second is an integer that describes the number of its rows, the third argument is an integer that describe its number of columns.


Function show() displays the content of the dynamic array on the screen as a 2-dimensional matrix, rows being rows, columns being columns.

Write a C function?
This is really basic





void show(char **array, int rows, int cols)


{


int i, j;


for (j = 0; j %26lt; rows; ++j)


for (i = 0; i %26lt; cols; ++i)


putchar(array[i][j]);


}





Its done
Reply:What school are you guys from?





Im tired of answering simple array questions. The fundamentals to alll of these questions are in the answers that I have provided. please read those and ask a question about something that you may not understand.
Reply:why won't u do it??





the logic is so simple..


it's all in your face and you can't even do that??





i think this question should have not been approve by


yahoo to be posted, imho.. :|


If you are using C language to implement the heterogeneous linked list, what pointer type will you use?

The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type

If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
no doubt you must use void pointer because it can be used to reference all data tyes.....


( NO MFC ) How I Know Mouse Is Over Button Control With C++ & Win32 API ?

please exaplain in code how i know mouse pointer is on my Button Control . Please Exaplian With C++ %26amp; Win32 API





( NO MFC ) --------Thanks .

( NO MFC ) How I Know Mouse Is Over Button Control With C++ %26amp; Win32 API ?
This Link will help you my friend





http://www.codeguru.com/cpp/controls/tre...

blazing star