Is there any way to output the actual array in c++
You can write a simple helper function to allow you to stream the array to an output stream (including but not limited to std::cout
):
#include <iostream>
// print an array to an output stream
// prints to std::cout by default
template <typename T, std::size_t N>
void print_array(const T(&a)[N], std::ostream& o = std::cout)
{
o << "{";
for (std::size_t i = 0; i < N-1; ++i)
{
o << a[i] << ", ";
}
o << a[N-1] << "}\n";
}
where a function template is used in order to deduce both the type and size of the array at compile time. You can use it like this:
#include <fstream>
int main()
{
int a[] = {1,2,3,4,5};
print_array(a); // prints {1, 2, 3, 4, 5} to stdout
std::string sa[] = {"hello", "world"};
print_array(sa, std::cerr); // prints {hello, world} to stderr
std::ofstream output("array.txt");
print_array(a, output); // prints {1, 2, 3, 4, 5} to file array.txt
}
This solution can be trivially generalized to deal with ranges and standard library containers. For even more general approaches, see here.
As for the side note, you cannot do that in C++. An array can only hold objects of one type.
How to print the array?
What you are doing is printing the value in the array at spot [3][3], which is invalid for a 3by3 array, you need to loop over all the spots and print them.
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
This will print it in the following format
10 23 42
1 654 0
40652 22 0
if you want more exact formatting you'll have to change how the printf is formatted.
How do I print the last element of an array in c
There is no defined term as empty array
Your array will always hold some value even if you dont initialize it explicitly
You need to define in your application how will you term it as empty may be by considering if its(element of array) value is 0 or some other value
Printing values of array in C
Use of %s
assume pointer to char array ending null symbol. But you give char instead pointer to char.
If you need one symbol - you should use %c
:
printf("%c", str1[0]);
for (int i=0; i<4; i++){
printf("This is it!!! %c ", str1[i]);
}
If you need string with offset - you should use pointers:
printf("%s", &str1[0]);
for (int i=0; i<4; i++){
printf("This is it!!! %s ", &str1[i]);
}
See printf reference.
EDIT1:
Solved...
#include <stdio.h>
#define MAX_LINE_CNT 3
int main(int argc, char* argv[])
{
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
char line[256];
char i, cnt = 0;
char str1[MAX_LINE_CNT][10], str3[MAX_LINE_CNT][10], * tmp;
int arr2[MAX_LINE_CNT], arr4[MAX_LINE_CNT];
while (fgets(line, sizeof(line), file)) {
tmp = strstr(line," -> ");
arr2[cnt] = 0; arr4[cnt] = 0;
sscanf(line,"%[^+ ]%x%*s", str1[cnt],&arr2[cnt]);
sscanf(tmp," -> %[^+ ]%x%*s", str3[cnt],&arr4[cnt]);
//cnt++;
if (++cnt >= MAX_LINE_CNT) break;
}
fclose(file);
for (i = 0; i < cnt; i++) {
printf("Array1[%d] %s \n", i+1, str1[i]);
printf("Array2[%d] %x \n", i+1, arr2[i]);
printf("Array3[%d] %s \n", i+1, str3[i]);
printf("Array4[%d] %x \n", i+1, arr4[i]);
}
return 0;
}
EDIT2:
It is strictly recomended to read chux's answer and c/c++ reference for understand what you doing and what the hell is going after compiling.
How to print an array of strings
The reason you can print strings
in main()
but not in print_array
is the result of how an array is converted to a pointer on access. What this means is that when you access an array (subject to 4 exceptions below) the array is converted to a pointer to the first element in the array. After the conversion takes place, as it does when you pass an array as a parameter to a function, you have only a pointer, not an array.
The C11 Standard (as well as the C17 Standard) reads as follows:
Array pointer conversion
(p3) Except when it is the operand of the sizeof
operator, the _Alignof
operator, or the unary '&'
operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue.
C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)
If you note above, when used with the sizeof
operator, and array is not converted to a pointer, so in main()
, sizeof(strings) / sizeof(strings[0])
provides the number of elements in the array of string. However, after you pass strings
to print_array
, the conversion to pointer has already occurred, so that in print_array
your attempted use of sizeof
results in:
size_t array_length = sizeof(a_pointer) / sizeof(a_char);
(which is 8
on x86_64, or 4
on x86)
You have two choices (1) pass the number of elements in your array as a second parameter to print_array
, or (2) make the last pointers in strings
NULL
(to be used as a sentinel value). Then in print_array
you can just iterate over strings[i]
until it is NULL
.
A couple of quick examples:
Passing the Number of Elements
#include <stdio.h>
void print_array (char **strings, size_t nptrs)
{
for (size_t i = 0; i < nptrs; i++)
printf("%s, ", strings[i]);
putchar ('\n');
}
int main(void) {
char *strings[] = { "Hello",
"Zerotom",
"new" };
print_array (strings, sizeof strings/sizeof *strings);
return 0;
}
Example Use/Output
$ ./bin/prnarray
Hello, Zerotom, new,
Adding a Sentinel NULL
to strings
#include <stdio.h>
void print_array (char **strings)
{
for (size_t i = 0; strings[i]; i++)
printf("%s, ", strings[i]);
putchar ('\n');
}
int main(void) {
char *strings[] = { "Hello",
"Zerotom",
"new",
NULL }; /* sentinel NULL */
print_array (strings);
return 0;
}
(same output)
There are at least a handful of ways to loop using either for
or while
loops and either using a pointer to strings
and pointer arithmetic, or using array indexing (the difference are simple semantics as you are doing the same thing). Look things over and let me know if you have further questions.
Returning an array using C
You can't return arrays from functions in C. You also can't (shouldn't) do this:
char *returnArray(char array []){
char returned [10];
//methods to pull values from array, interpret them, and then create new array
return &(returned[0]); //is this correct?
}
returned
is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.
You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.
Option 1:
dynamically allocate the memory inside of the function (caller responsible for deallocating ret
)
char *foo(int count) {
char *ret = malloc(count);
if(!ret)
return NULL;
for(int i = 0; i < count; ++i)
ret[i] = i;
return ret;
}
Call it like so:
int main() {
char *p = foo(10);
if(p) {
// do stuff with p
free(p);
}
return 0;
}
Option 2:
fill a preallocated buffer provided by the caller (caller allocates buf
and passes to the function)
void foo(char *buf, int count) {
for(int i = 0; i < count; ++i)
buf[i] = i;
}
And call it like so:
int main() {
char arr[10] = {0};
foo(arr, 10);
// No need to deallocate because we allocated
// arr with automatic storage duration.
// If we had dynamically allocated it
// (i.e. malloc or some variant) then we
// would need to call free(arr)
}
Changing array inside function in C
In c you can't pass a variable by reference, the array
variable that you assign inside the function contains initially the same address as the passed pointer, but it's a copy of it so modifying it will not alter the passed pointer.
You need to pass the address of the pointer in order to be able to alter it, like this
// Change the pointer of the array
void change(int **array, int length)
{
*array = malloc(length * sizeof(int));
if (*array == NULL)
return;
for (int i = 0 ; i < length ; i++)
(*array)[i] = 1;
}
Then in main()
you cannot assign to an array, doing so through this kind of function is surely undefined behavior. The array defined in main()
is allocated on the stack and you cannot assign anything to an array since they are non-writeable lvalues so you cannot make it point to a heap memory location obtained with malloc()
, you need to pass a pointer like this
int *array;
change(&array, length);
free(array);
If you want the function to replace the previous array, it will have to free()
the malloc()
ed data (note that passing NULL
to free()
is well defined), so
// Change the pointer of the array
void change(int **array, int length)
{
free(*array);
*array = malloc(length * sizeof(int));
if (*array == NULL)
return;
for (int i = 0 ; i < length ; i++)
(*array)[i] = 1;
}
then in main()
int *array;
array = NULL;
change(&array, length);
change(&array, length);
change(&array, length);
change(&array, length);
free(array);
will do what you apparently want.
Related Topics
Are There in X86 Any Instructions to Accelerate Sha (Sha1/2/256/512) Encoding
Segmentation Fault Before Main() When Using Glut, and Std::String
Can Someone Explain About Linux Library Naming
How to Bit Shift a Long by More Than 32 Bits
Compiler Support for Upcoming C++0X
How to Call a Constructor on an Already Allocated Memory
What Expressions Create Xvalues
How to Reproduce Tcp Protocol 3-Way Handshake with Raw Sockets Correctly
C++11 Member Initialization List Ambiguity
What Is the Overhead Cost of an Empty Vector
Calculate Md5 of a String in C++
Hash Function for User Defined Class. How to Make Friends?
How to Convert a Tchar Array to Std::String
How to Make Camera Follow a 3D Object in Opengl