How to Use Arrays in C++

What does ** do in C language? [duplicate]

In C arguments are passed by values. For example if you have an integer varaible in main

int main( void )
{
int x = 10;
//...

and the following function

void f( int x )
{
x = 20;
printf( "x = %d\n", x );
}

then if you call the function in main like this

f( x );

then the parameter gets the value of variable x in main. However the parameter itself occupies a different extent in memory than the argument. So any changes of the parameter in the function do not influence to the original variable in main because these changes occur in different memory extent.

So how to change the varible in main in the function?

You need to pass a reference to the variable using pointers.

In this case the function declaration will look like

void f( int *px );

and the function definition will be

void f( int *px )
{
*px = 20;
printf( "*px = %d\n", *px );
}

In this case it is the memory extent occupied by the original variable x is changed because within the function we get access to this extent using the pointer

    *px = 20;

Naturally the function must be called in main like

f( &x );

Take into account that the parameter itself that is the pointer px is as usual a local variable of the function. That is the function creates this variable and initializes it with the address of variable x.

Now let's assume that in main you declared a pointer for example the following way

int main( void )
{
int *px = malloc( sizeof( int ) );
//..

And the function defined like

void f( int *px )
{
px = malloc( sizeof( int ) );

printf( "px = %p\n", px );
}

As parameter px is a local variable assigning to it any value does not influence to the original pointer. The function changes a different extent of memory than the extent occupied by the original pointer px in main.

How to change the original pointer in the function?
Just pass it by reference!

For example

f( &px );
//...

void f( int **px )
{
*px = malloc( sizeof( int ) );

printf( "*px = %p\n", *px );
}

In this case the value stored in the original pointer will be changed within the function because the function using dereferencing access the same memory extent where the original pointer was defined.

How to define an array in C

What you mean is the following

#include <stdio.h>
#include <limits.h>

#define N 5

int main( void )
{
int array[N] = { 1, 3, 2, 5, 4 };

int min = INT_MAX;
int max = INT_MIN;

for ( size_t i = 0; i < N; i++ )
{
if ( array[i] < min ) min = array[i];
if ( max < array[i] ) max = array[i];
}

printf( "The minimum is %i\n", min );
printf( "The maximum is %i\n", max );

return 0;
}

The program output is

The minimum is 1
The maximum is 5

As for your program then it contains invalid constructions according to the C grammar.

In C++ the loop can look the same way as you showed.

#include <iostream>
#include <limits>

int main()
{
const size_t N = 5;
int array[N] = { 1, 3, 2, 5, 4 };

int min = std::numeric_limits<int>::max();
int max = std::numeric_limits<int>::min();

for ( int x : array )
{
if ( x < min ) min = x;
if ( max < x ) max = x;
}

std::cout << "The minimum is " << min << std::endl;
std::cout << "The maximum is " << max << std::endl;

return 0;
}

Take into account that there is no sense to declare the array like global.

As for the array definition in C then you can define it either like

int array[5] = { 1, 3, 2, 5, 4 };

(or using some named constant instead of the number 5)

or like

int array[] = { 1, 3, 2, 5, 4 };

In the last case the number of elements is equal to the number of the initializers. Or even you can use the following initialization

int array[] = { [0] = 1, [1] = 3, [2] = 2, [3] = 5, [4] = 4 };

How do I determine the size of my array in C?

Executive summary:

int a[17];
size_t n = sizeof(a)/sizeof(a[0]);

Full answer:

To determine the size of your array in bytes, you can use the sizeof
operator:

int a[17];
size_t n = sizeof(a);

On my computer, ints are 4 bytes long, so n is 68.

To determine the number of elements in the array, we can divide
the total size of the array by the size of the array element.
You could do this with the type, like this:

int a[17];
size_t n = sizeof(a) / sizeof(int);

and get the proper answer (68 / 4 = 17), but if the type of
a changed you would have a nasty bug if you forgot to change
the sizeof(int) as well.

So the preferred divisor is sizeof(a[0]) or the equivalent sizeof(*a), the size of the first element of the array.

int a[17];
size_t n = sizeof(a) / sizeof(a[0]);

Another advantage is that you can now easily parameterize
the array name in a macro and get:

#define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))

int a[17];
size_t n = NELEMS(a);

How to use scanf properly with Arrays in a loop in C?

You have several 'points of confusion', it would seem!

First, the return value of the scanf_s function is not the actual value read, but rather the number of items successfully scanned. So, your assignments like sExampleEmployee[i].ccFirstName = scanf_s(... won't do anything like what you appear to think they will.

Second, your sExampleEmployee-> usage won't get the structure field of any structure but the first - as an array name used without an [] index will, effectively, be a pointer to the first member of the array. (See next point on arrays!)

Third (and very important), you have not assigned any memory to the ccFirstName and ccLastName structure members - they are just uninitialized pointers. You would be better off declaring them as arrays of fixed length: long enough to hold any possible input plus the required terminating nul character.

Finally (a more subtle problem), when you have a string argument (corresponding to the %s format specifier) in the scanf_s function, you need to add an extra argument (immediately after the string) specifying the size of that string buffer (to prevent reading in too many characters).

So, with these points in mind, you should re-define your structure, and re-write your input loop, to something along these lines:

#define MAXNAMELEN 100 // Use whatever value you want - this will allow 99 letters
struct Employee
{
char ccFirstName[MAXNAMELEN];
char ccLastName[MAXNAMELEN];
int iAge;
};
//...
for (int i = 0; i < 3; i++)
{
printf("Geben Sie den Namen :");
scanf_s("%s", sExampleEmployee[i].ccFirstName, MAXNAMELEN); // Arrays (strings) are automatically...
scanf_s("%s", sExampleEmployee[i].ccLastName, MAXNAMELEN); // ... pointers!
scanf_s("%d", &(ExampleEmployee[i].iAge)); // But integers need the "&"
}

EDIT: For more information on the scanf_s function, see here. The important part (for your case) is this:

Unlike scanf and wscanf, scanf_s and wscanf_s require you to specify
buffer sizes for some parameters. Specify the sizes for all c, C, s,
S, or string control set [] parameters. The buffer size in characters
is passed as an additional parameter. It immediately follows the
pointer to the buffer or variable.

NOTE: as can be seen in the MS documentation, the size argument after the pointer for %s has type unsigned for Microsoft's implementation of scanf_s, whereas it must have type rsize_t as per the C Standard Annex K. Type rsize_t is specified there as being the same as size_t which may have a different size from unsigned int, and indeed it does on 64-bit architectures for both Linux and Windows, so the MS doc specifies that The size parameter is of type unsigned, not size_t. Use a static cast to convert a size_t value to unsigned for 64-bit build configurations, A very peculiar approach to portability.

For this and other reasons, scanf_s should not be used in portable code.

Initialize all elements of C array to an integer [duplicate]

Use a loop to assign the desired value to each elements. In typical current computer and compiler with optimization enabled, the cost of memory access should be higher than the cost of looping, so you should only consider the cost of looping only after you actually found it is too slow.

#include <stdio.h>

int main() {
int A[10];
for (size_t i = 0; i < sizeof(A) / sizeof(*A); i++) {
A[i] = -2;
}

printf("%d",A[3]);
}

Arrays in C programming

The existence of minvals would imply that you are expected to calculate the minimum value of each 'row' of table before then moving on to printing. As it stands, had your program properly calculated the minimum values of each array, your printing would be rather out of order.

There's no need to do any tricky, manual pointer manipulation. Simple array subscription is much clearer.

Let's start simple and return to basics by looking at the way we find the minimum value in a one dimensional array, as it is the core of this problem.

To find the minimum value in an array we need a few things to start:

  • An array
  • The length of the array
  • An initial value to compare against

The array itself is obviously each subarray of table, and the length in this case is known to be NUMCOLS. Our initial value should either be INT_MAX (or another type-appropriate maximum constant found <limits.h>), such that every element in the array is equal to or less than our initial value, or a value from the array itself.

Often times we opt for the second option here, choosing the first element in the array as our initial value, and comparing it to the second and onward elements.

As such, finding the minimum value in a single 'row' would look like this

const int row[NUMCOLS] = { 9, 2, 5 };
int min = row[0];

for (int i = 1; i < NUMCOLS; i++)
if (row[i] < min)
min = row[i];

but since we want to find and record the minimum value of each 'row' in table, we're going to use a nested loop. Instead of the min variable from before, we store each value in the associated index of our minvals array.

for (i = 0; i < NUMROWS; i++) {
minvals[i] = table[i][0];

for (j = 1; j < NUMCOLS; j++)
if (table[i][j] < minvals[i])
minvals[i] = table[i][j];
}

When it comes time to print, we're going to repeat our nested loop. Our inner loop prints each element of each 'row' of table, and we end each iteration of the outer loop by printing the value found in minvals with the same index of our 'row'.

for (i = 0; i < NUMROWS; i++) {
for (j = 0; j < NUMCOLS; j++)
printf("%6d", table[i][j]);

printf(":%6d\n", minvals[i]);
}

Here's a working example.

#include <stdio.h>
#define NUMROWS 2
#define NUMCOLS 3

int main(void) {
const int table[NUMROWS][NUMCOLS] = {
{ 9, 2, 5 },
{ 3, -4, -12 }
};
int minvals[NUMROWS];
int i, j;

for (i = 0; i < NUMROWS; i++) {
minvals[i] = table[i][0];

for (j = 1; j < NUMCOLS; j++)
if (table[i][j] < minvals[i])
minvals[i] = table[i][j];
}

puts("Table value: minimum values");

for (i = 0; i < NUMROWS; i++) {
for (j = 0; j < NUMCOLS; j++)
printf("%6d", table[i][j]);

printf(":%6d\n", minvals[i]);
}
}

A good further exercise for you would be to compose the logic of the inner loop for finding minimum values into a more generic function. Its function signature would look like

int min(int *array, size_t length);

allowing it to work on arrays of varying sizes. Then our outer loop could be as simple as:

for (i = 0; i < NUMROWS; i++)
minvals[i] = min(table[i], NUMCOLS);

How to print all data from an array in C?

Since you have a 2-dimensional array, you should use nested loops for each dimension, and access the elements using 2 indexes.

To get the number of elements in an array use sizeof array / sizeof array[0].

for (int i = 0; i < sizeof array / sizeof array[0]; i++) {
for (int j = 0; j < sizeof array[i] / sizeof array[i][0]; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}


Related Topics



Leave a reply



Submit