C Questions

1. C++ questions

2 excellent test

http://warp.povusers.org/c++test/

3. More C++ questions

array

C:

int xyz[][2] = {{5,8},{4,5},{1,2}}; 
//declaration of `a' as multidimensional array must have bounds for all dimensions except the first
char first[]={'x','y','z','\0'};
 
char second[]="abcd";
char *third = "abc"; //difference from previous, it is read only from some compile , ie, you can not change like: *(third+1) = 'k';
 
int main(int argc, char * argv[])  //argv[0] is the program name

Java Code

int[][] matrix;
public static void main(String argv[])  //argv[0] is the 1st parameter

int abc[3];
int* p;
actually a = &(a[0])

If you declare an array as a function argument, what you’re really declaring is a pointer. So in the following example, func1( ) and func2( ) effectively have the same argument lists:

void func1(int a[], int size) {
  for(int i = 0; i < size; i++)
    a[i] = i * i - i;
}
 
void func2(int* a, int size) {
  for(int i = 0; i < size; i++)
    a[i] = i * i + i;
}
int a[5];
 
func1(a,5);
func2(a,5);

pointer and array;

http://c-faq.com/aryptr/ptrtoarray.html

How do I declare a pointer to an array?

A: Usually, you don't want to. When people speak casually of a pointer to an array, they usually mean a pointer to its first element.

Instead of a pointer to an array, consider using a pointer to one of the array's elements. Arrays of type T decay into pointers to type T (see question 6.3), which is convenient; subscripting or incrementing the resultant pointer will access the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays (see below), and are generally useful only when operating on arrays of arrays, [footnote] if at all. (See also question 6.18.)

If you really need to declare a pointer to an entire array, use something like “int (*ap)[N];” where N is the size of the array. (See also question 1.21.) If the size of the array is unknown, N can in principle be omitted, but the resulting type, “pointer to array of unknown size,” is useless.

Here is an example showing the difference between simple pointers and pointers to arrays. Given the declarations

int a1[3] = {0, 1, 2};
int a2[2][3] = {{3, 4, 5}, {6, 7, 8}};
int *ip;        /* pointer to int */
int (*ap)[3];        /* pointer to int array [3]  , int (*ap)[N];  N is the columns of array*/
 
 int *ap2[10];  /* this is an array of pointers. In declarations, the brackets [] which describe arrays have higher 
                         precedence than the * which describes pointers. It looks like the * and the [] are both next to 
                        the identifier ap2, but since [] has higher precedence it means that the brackets are ``closer'' 
                        -- ap2 is an array first , thus array of pointers*/

you could use the simple pointer-to-int, ip, to access the one-dimensional array a1:

ip = a1;
    printf("%d ", *ip);
    ip++;
    printf("%d\n", *ip);

This fragment would print

0 1

An attempt to use a pointer-to-array, ap, on a1:

ap = &a1;
    printf("%d\n", **ap);
    ap++;                /* WRONG */
    printf("%d\n", **ap);        /* undefined */

would print 0 on the first line and something undefined on the second (and might crash). The pointer-to-array would only be at all useful in accessing an array of arrays, such as a2:
ap = a2;
    printf("%d %d\n", (*ap)[0], (*ap)[1]);
    ap++;        /* steps over entire (sub)array */
    printf("%d %d\n", (*ap)[0], (*ap)[1]);

This last fragment would print

3 4
6 7

See also question 6.12.

Micro preprocessor

#define P(EXP) \
  cout << "expression" #EXP "has value" << ": " << EXP << endl;

this one uses a preprocessor feature called stringizing (implemented with the ‘ #’ sign before an expression) which takes any expression and turns it into a character array. This is quite convenient, since it allows the expression to be printed, followed by a colon, followed by the value of the expression.

## is used to concat string, like A##B
#define f(a,b)  a##b
int ab=10;
printf("%d",f(a,b)); //will print out 10

2 dimension array

http://c-faq.com/aryptr/dynmuldimary.html

#include <stdlib.h>
<第一种方式>
int **array1 = malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
array1[i] = malloc(ncolumns * sizeof(int));

//sizeof(*array1) = sizeof(int *) and sizeof(**array1) = sizeof(int)

<第二种方式>
you can simulate a two-dimensional array with a single, dynamically-
allocated one-dimensional array:

int *array2 = malloc(nrows * ncolumns * sizeof(int));
However, you must now perform subscript calculations manually, accessing the
i,jth element with the expression :array3[i * ncolumns + j]

int **array2 = (int **)malloc(nrows * sizeof(int *));
array2[0] = malloc(nrows * ncolumns * sizeof(int));
for(i = 1; i < nrows; i++)
array2[i] = array2[0] + i * ncolumns;

<第三种方式>
Yet another option is to use pointers to arrays:

int (*array4)[NCOLUMNS] = malloc(nrows * sizeof(*array4));

<第四种方式>

int (*array5)[NROWS][NCOLUMNS] = malloc(sizeof(*array5));
accesses to array5 look like (*array5)[i][j]

http://c-faq.com/aryptr/dynmuldimary.html

If you are passing a two-dimensional array to a function:

int array[NROWS][NCOLUMNS];
f(array);

the function's declaration must match:

void f(int a[][NCOLUMNS])
{ … }

or

void f(int (*ap)[NCOLUMNS]) /* ap is a pointer to an array */
{ … }

http://c-faq.com/aryptr/pass2dary.html

in addition:
http://c-faq.com/aryptr/aryparmsize.html
http://c-faq.com/aryptr/aryptrparam.html
Why doesn't sizeof properly report the size of an array when the array is a parameter to a function? I have a test routine

f(char a[10])
{
int i = sizeof(a);
printf("%d\n", i);
}

and it prints 4, not 10.

this is because the compiler turns around and pretends that you'd written a pointer declaration, since that's what the function will in fact receive:

void f(char *a)
{ … }

++++ sizeof
in file 1, you have int a[]={2,3};
in file 2 you have : extern int a[]; int c = sizeof*(a);
this doesn't work, because sizeof is compiler time, extern is link time;
so how do you the array's size? you must explict define it like #define ARRAY_SIZE 2;
http://c-faq.com/aryptr/extarysize.html

I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn't it work?

A: In one source file you defined an array of characters and in the other you declared a pointer to characters. The declaration extern char *a does not declare an array and therefore does not match the actual definition. The type pointer-to-type-T is not the same as array-of-type-T. Use extern char a[].

I have a char * pointer that happens to point to some ints, and I want to step it over them. Why doesn't

((int *)p)++;

work?

A: In C, a cast operator does not mean “pretend these bits have a different type, and treat them accordingly”; it is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++. (It is either an accident or a deliberate but nonstandard extension if a particular compiler accepts expressions such as the above.) Say what you mean: use

p = (char *)((int *)p + 1);

or (since p is a char *) simply

p += sizeof(int);

or (to be really explicit)

int *ip = (int *)p;
p = (char *)(ip + 1);

How to scan a string till we hit a new line using scanf()?

Use

scanf("%[^\n]", address);

How would you find the size of structure without using sizeof()?

Try using pointers

struct MyStruct
{
int i;
int j;
};

int main()
{
struct MyStruct *p=0;
int size = ((char*)(p+1))-((char*)p);
printf("\nSIZE : [%d]\nSIZE : [%d]\n", size);
return 0;
}

Write C code to check if an integer is a power of 2 or not in a single line?

Even this is one of the most frequently asked interview questions. I really dont know whats so great in it. Nevertheless, here is a C program

Method1

if(!(num & (num - 1)) && num)
{
// Power of 2!
}

Method2

if(((~i+1)&i)==i)
{
//Power of 2!
}

implements a?b:c function without if else

Write a function to implement a ternary operator a?b:c
without using any conditional statements like if,for,while etc..
you are allowed to you any operators like &, |, ^ etc…
your function can use return statement.

int Ternary(int a, int b, int c)
{
.
.
.
return …
}

My soln employs helper function
int fun0or1(int num){
return num !=0 ;
}

int ternary(int a,int b,int c){

int e = fun0or1(a);//a can be any expression
return ( e*b + (1-e) *c)
}

tricks and tips of C++ I/O

http://www.augustcouncil.com/~tgibson/tutorial/iotips.html

a MyString class , very instructive

MyString Class

pointers

typedef int **ppMYARRAY[7];

Thats array of [7] pointers to pointers to int

typedef int *(*ppMYARRAY)[7];
pointer to an array of [7] pointers to int

There's a program to help with the complicated ones.
http://packages.debian.org/stable/devel/cdecl

Here's an article on how to read those complex beasties.
http://www.codeproject.com/cpp/complex_declarations.asp

acccess

class B : public A { };

means that users of B (including subclasses of B) can see all that is available from A.

class B : protected A { };

means that users of B can't see things from A, but subclasses of B can.

class B : private A { };

means that users of B (including subclasses of B) can't see what is available from A.

VPTR

The compiler secretly inserts code into the beginning of the constructor that initializes the VPTR….. http://www.codeguru.com/cpp/tic/tic0162.shtml


3. Books

Thinking in C++ 2nd ed

C# and .Net

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License