I'm having issues on printing an array, that's what I'm doing:
#include <stdio.h>
#define DIM 5
int main () {
double data[DIM] = {128.5, 131.4, 133.2, 127.1, 130.9};
printf("%lf", data[DIM]);
return 0;
}
The answer is always 0.000000.
I've also tried to put the values separately, like this:
#include <stdio.h>
#define DIM 5
int main () {
double data[DIM];
data[0]=128.5;
data[1]=131.4;
data[2]=133.2;
data[3]=127.1;
data[4]=130.9;
printf("%lf", data[DIM]);
return 0;
}
And still the answer is always 0.000000.
Could someone please help. Thank you in advance!
As 4386427 and 500 - Internal Server Error pointed out, there are two issues at work here.
You are trying to print an out-of-bounds index. When you make an array of length 5, indexes go from 0 to 4.
More importantly, there is no specific "print array" function that I am aware of. Your best bet is to create a loop that prints each element of the array.
void printDoubleArray(double arr[], int length)
{
printf("[");
if (length > 0)
{
printf("%f", arr[0]);
}
for (int i = 1; i < length; i++)
{
printf(", %f", arr[i]);
}
printf("]\n");
}
In this call
printf("%lf", data[DIM]);
you are trying to output a non-existent element of the array with the index DIM while the valid range of indices for the array is [0, DIM). This record means that 0 is included in the range as a valid index and DIM is excluded from the range.
As a result the call of printf invokes undefined behavior.
Also you should use the conversion specifier f instead of lf. The length modifier l does not have an effect used with the conversion specifier f. So it is just redundant.
You can not output a whole array except character arrays (by means of the conversion specifier s).
To output the whole array you need to use a loop as for example
for ( size_t i = 0; i < DIM; i++ )
{
printf( "%.1f ", data[i] );
}
putchar( '\n' );
Here is a demonstrative program.
#include <stdio.h>
#define DIM 5
int main(void)
{
double data[DIM] = { 128.5, 131.4, 133.2, 127.1, 130.9 };
for ( size_t i = 0; i < DIM; i++ )
{
printf( "%.1f ", data[i] );
}
putchar( '\n' );
return 0;
}
The program output is
128.5 131.4 133.2 127.1 130.9
C, the language itself, does not have array bounds checking. You want the element one past the end? sure thing. You want the element a million past the end? sure you can ask for that too (who knows what will happen but you can ask for it)
If your compiler supports it, you can get more robust error reporting. Not C standard but helpful nonetheless.
GCC:
Compile with -fsanitize=address and at run-time the sanitizer will catch this overrun:
=======================
==220715==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffed8db4988 at pc 0x559ba54babcc bp 0x7ffed8db4920 sp 0x7ffed8db4910
READ of size 8 at 0x7ffed8db4988 thread T0
#0 0x559ba54babcb in main /tmp/overrun.c:9
clang:
In addition to the run-time sanitizer (-fsanitize=address), Clang can also point out your problem at compile time:
printf("%lf", data[DIM]);
^ ~~~
overrun.c:7:5: note: array 'data' declared here
double data[DIM] = {128.5, 131.4, 133.2, 127.1, 130.9};
^
1 warning generated.
Related
I'm trying to create a complete C program to read ten alphabets and display them on the screen. I shall also have to find the number of a certain element and print it on the screen.
#include <stdio.h>
#include <conio.h>
void listAlpha( char ch)
{
printf(" %c", ch);
}
int readAlpha(){
char arr[10];
int count = 1, iterator = 0;
for(int iterator=0; iterator<10; iterator++){
printf("\nAlphabet %d:", count);
scanf(" %c", &arr[iterator]);
count++;
}
printf("-----------------------------------------");
printf("List of alphabets: ");
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
listAlpha(arr[x]);
}
printf("%c",arr);
return 0;
}
int findTotal(){
}
int main(){
readAlpha();
}
The code should be added in the findTotal() element. The output is expected as below.
Output:
List of alphabets : C C C A B C B A C C //I've worked out this part.
Total alphabet A: 2
Total alphabet B: 2
Total alphabet C: 6
Alphabet with highest hit is C
I use an array to count the number of the existence of each character,
I did this code but the display of number of each character is repeated in the loop
int main()
{
char arr[100];
printf("Give a text :");
gets(arr);
int k=strlen(arr);
for(int iterator=0; iterator<k; iterator++)
{
printf("[%c]",arr[iterator]);
}
int T[k];
for(int i=0;i<k;i++)
{
T[i]=arr[i];
}
int cpt1=0;
char d;
for(int i=0;i<k;i++)
{int cpt=0;
for(int j=0;j<k;j++)
{
if(T[i]==T[j])
{
cpt++;
}
}
if(cpt>cpt1)
{
cpt1=cpt;
d=T[i];
}
printf("\nTotal alphabet %c : %d \n",T[i],cpt);
}
printf("\nAlphabet with highest hit is : %c\n",d,cpt1);
}
There is no way to get the number of elements You write in an array.
Array in C is just a space in the memory.
C does not know what elements are actual data.
But there are common ways to solve this problem in C:
as mentioned above, create an array with one extra element and, fill the element after the last actual element with zero ('\0'). Zero means the end of the actual data. It is right if you do not wish to use '\0' among characters to be processed. It is similar to null-terminated strings in C.
add the variable to store the number of elements in an array. It is similar to Pascal-strings.
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE 10
char array[ARRAY_SIZE + 1];
int array_len(char * inp_arr) {
int ret_val = 0;
while (inp_arr[ret_val] != '\0')
++ret_val;
return ret_val;
}
float array_with_level[ARRAY_SIZE];
int array_with_level_level;
int main() {
array[0] = '\0';
memcpy(array, "hello!\0", 7); // 7'th element is 0
printf("array with 0 at the end\n");
printf("%s, length is %d\n", array, array_len(array));
array_with_level_level = 0;
const int fill_level = 5;
int iter;
for (iter = 0; iter < fill_level; ++iter) {
array_with_level[iter] = iter*iter/2.0;
}
array_with_level_level = iter;
printf("array with length in the dedicated variable\n");
for (int i1 = 0; i1 < array_with_level_level; ++i1)
printf("%02d:%02.2f ", i1, array_with_level[i1]);
printf(", length is %d", array_with_level_level);
return 0;
}
<conio.h> is a non-standard header. I assume you're using Turbo C/C++ because it's part of your course. Turbo C/C++ is a terrible implementation (in 2020) and the only known reason to use it is because your lecturer made you!
However everything you actually use here is standard. I believe you can remove it.
printf("%c",arr); doesn't make sense. arr will be passed as a pointer (to the first character in the array) but %c expects a character value. I'm not sure what you want that line to do but it doesn't look useful - you've listed the array in the for-loop.
I suggest you remove it. If you do don't worry about a \0. You only need that if you want to treat arr as a string but in the code you're handling it quite validly as an array of 10 characters without calling any functions that expect a string. That's when it needs to contain a 0 terminator.
Also add return 0; to the end of main(). It means 'execution successful' and is required to be conformant.
With those 3 changes an input of ABCDEFGHIJ produces:
Alphabet 1:
Alphabet 2:
Alphabet 3:
Alphabet 4:
Alphabet 5:
Alphabet 6:
Alphabet 7:
Alphabet 8:
Alphabet 9:
Alphabet 10:-----------------------------------------List of alphabets: A B C D E F G H I J
It's not pretty but that's what you asked for and it at least shows you've successfully read in the letters. You may want to tidy it up...
Remove printf("\nAlphabet %d:", count); and insert printf("\nAlphabet %d: %c", count,arr[iterator]); after scanf(" %c", &arr[iterator]);.
Put a newline before and after the line of minus signs (printf("\n-----------------------------------------\n"); and it looks better to me.
But that's just cosmetics. It's up to you.
There's a number of ways to find the most frequent character. But at this level I recommend a simple nested loop.
Here's a function that finds the most common character (rather than the count of the most common character) and if there's a tie (two characters with the same count) it returns the one that appears first.
char findCommonest(const char* arr){
char commonest='#'; //Arbitrary Bad value!
int high_count=0;
for(int ch=0;ch<10;++ch){
const char counting=arr[ch];
int count=0;
for(int c=0;c<10;++c){
if(arr[c]==counting){
++count;
}
}
if(count>high_count){
high_count=count;
commonest=counting;
}
}
return commonest;
}
It's not very efficient and you might like to put some printfs in to see why!
But I think it's at your level of expertise to understand. Eventually.
Here's a version that unit-tests that function. Never write code without a unit test battery of some kind. It might look like chore but it'll help debug your code.
https://ideone.com/DVy7Cn
Footnote: I've made minimal changes to your code. There's comments with some good advice that you shouldn't hardcode the array size as 10 and certainly not litter the code with that value (e.g. #define ALPHABET_LIST_SIZE (10) at the top).
I have used const but that may be something you haven't yet met. If you don't understand it and don't want to learn it, remove it.
The terms of your course will forbid plagiarism. You may not cut and paste my code into yours. You are obliged to understand the ideas and implement it yourself. My code is very inefficient. You might want to do something about that!
The only run-time problem I see in your code is this statement:
printf("%c",arr);
Is wrong. At this point in your program, arr is an array of char, not a single char as expected by the format specifier %c. For this to work, the printf() needs to be expanded to:
printf("%c%c%c%c%c%c%c%c%c%c\n",
arr[0],arr[1],arr[2],arr[3],arr[4],
arr[5],arr[6],arr[7],arr[8],arr[9]);
Or: treat arr as a string rather than just a char array. Declare arr as `char arr[11] = {0};//extra space for null termination
printf("%s\n", arr);//to print the string
Regarding this part of your stated objective:
"I shall also have to find the number of a certain element and print it on the screen. I'm new to this. Please help me out."
The steps below are offered to modify the following work
int findTotal(){
}
Change prototype to:
int FindTotal(char *arr);
count each occurrence of unique element in array (How to reference)
Adapt above reference to use printf and formatting to match your stated output. (How to reference)
I am trying to write an array (2x20000) on C. The test code is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double test( int smod )
{
//
// test subroutine
//
double vect_fma[2][20000];
int i;
// write on file //
FILE *f = fopen("file.txt", "w");
///////////////////
for( i = 1; i < 20001; i = i + 1 ){
// allocate the vector for the fma analysis
vect_fma[1][i] = i*smod;
vect_fma[2][i] = i*smod;
if ( i%smod == 0 )
fprintf(f, "%f %f %f \n", 1.0*i, vect_fma[1][i],vect_fma[2][i] );
}
fclose(f);
return 0;
}
int smod;
void main()
{
smod = 10; // every 10 print the output
test(smod); // call the function
}
I compiled the code with gcc test.c -lm -o test and I received Segmentation fault (core dumped) .
As far as I am new on C, I understand that "the compiler tries to store it on the stack" and a solution could be the one presented in the linked page....but that solution looks quite weird (and complex to understand) if compared with more simple fortran declaration of array real(8), dimension(n:m) :: vect_fma which I can put in a subroutine or in a function without problems.
Is maybe that the declaration I wrote in the code is similar to the fortran real(8), dimension(n,m),allocatable :: vect_fma one ?
So the question is, it exist a simpler way in C to declare an array inside a function ?
Many thanks to everybody.
You have out of bounds access in multiple places, which is undefined behaviour.
In C, an array index ranges from 0 to N-1, not from 1 to N. That means, rewriting the loop part to:
for( i = 0; i < 20000; i = i + 1 ){
// allocate the vector for the fma analysis
vect_fma[0][i] = i*smod;
vect_fma[1][i] = i*smod;
if ( i%smod == 0 )
fprintf(f, "%f %f %f \n", 1.0*i, vect_fma[0][i],vect_fma[1][i] );
}
It's possible 2x20000 doubles might be too big for the stack size on your system, you'd better off fixing the undefined behaviours first
and see if the problem disappears.
The problem is your for loop. You should begin with an iteration where i=0 and end with an iteration where i=19999. Your code begins with an iteration where i=1 and ends with an iteration where i=20000.
The problem is that that there is no 20000th element of your array, only a 19999th (zero indexed). When you access the the 20000th element your accessing system memory that was never allocated for your program which is causing a segmentation fault.
Fix your for loop and you should be good.
Since the printf function returns an integer value every time it is used (the number of characters written on the screen), shouldn't it be compulsory to store this value in an int variable every time printf is called?
Edit:
If a function is returning certain value, why doesn't C make it necessary to store the value at the time of the function call?
It can be, only if it is necessary.
If we don't care don't want the return value to be used. there is no use storing the same.
If you have an idea how you are going to use x then of course you may write
int x = printf( "text" );
Otherwise the return value of the function is simply discarded because it is not used.
And in most cases programmers do not find a useful application of the return value of printf.
However sometimes it can be used for example to print tables with aligned columns.
For example
int n = printf( "%s", SomeString );
if ( n < COLUMN_WIDTH ) printf( "%*c", COLUMN_WIDTH - n, ' ' );
Consider this simple program
#include <stdio.h>
int main( void )
{
const int COLUMN_WIDTH = 20;
int n = printf( "%s", "Hello" );
if ( n < COLUMN_WIDTH ) printf( "%*c", COLUMN_WIDTH - n, ' ' );
printf( "%s", "World" );
}
Its output is
Hello World
Here is another example where the return value of printf finds a useful application.
Let's assume that you need to output a sequence of numbers separated with a comma like for example
1, 2, 3, 4, 5, 6, 7, 8, 9
How to output such a sequence using only a single loop without placing print statements outside the loop?
Here is a program that shows how it can be done based on using the return value of the function printf. :) Try it.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( void )
{
size_t n = 0;
printf( "Enter the number of elements in the array (greater than 0): " );
scanf( "%zu", &n );
if ( n == 0 ) exit( 1 );
int a[n];
srand( ( unsigned int )time( NULL ) );
size_t i;
for ( i = 0; i < n; i++ ) a[ i ] = rand() % n;
i = 0;
do
{
printf( "%d", a[ i ] );
} while ( ++i < n && printf( ", ") > 0 );
return 0;
}
As for your program
int foo(int x) {
return x;
}
int main() {
foo(10);
}
then calling function foo does not have any effect. It does nothing and in fact can be removed. And not all compilers issue a message for your program. It seems that the compiler you are using has a compiler option that forse the compiler to consider warnings like errors. So your compiler wants that you would pay the attention to that the call of the function does not have any effect. It is possible that you made a logical error.
On the other hand calling function printf has a visible effect.
If you think that your C program is going to be translated into an assembly language (x86 assembly for example), reading the return value of a function is just a matter of reading the value stored in the 'eax' register of your CPU.
The C programming language was historically written to be a language simple to parse and compile on a very limited (for today standards) PDP-11 computer.
Early C compilers (well, some of them) accepted functions declared without a return type AND without a return, like the following:
myFunc(int *x)
{
*x = *x + *x;
}
This is a function that those early C compilers would interpret as
int myFunc(int *x)
{
*x = *x + *x;
return 0;
}
So the answer to your question can be 'because of legacy code'.
There are however situations when the return value should or must be checked.
Rule 16.10 from MISRA C guidelines states that:
"If a function returns error information, then that error information shall be tested".
So if you need to be sure the printf() has printed something, if you're using the return value as an 'error information', following MISRA guidelines, you must check that value.
You can store the return value if you need it, for example to be sure that you are outputting the desired number of characters (it sounds very unlikely that one has this needs, especially considering that in production you usually have more comprehensive logging modules to handle your outputs).
You can also explicitly say that you don't care about that return value to the compiler with a (void) as in
(void) printf("hello world\n");
Note that this has no implications other than suppressing warnings of some tools (e.g., lint)
If a function is returning certain value, why doesn't C make it necessary to store the value at the time of the function call?
This is probably worse from the normal C programming style point of view: You have created a local variable with a value, but you don't use it:
int x;
x = printf(...);
would give a warning that you're not using x for anything. You would have to do this to solve both open ends:
if (printf(...)<EXPECTED_OUTPUT_BYTES) exit(1);
or similar. Luckily, exit doesn't return anything.
As others have said, you are free to ignore the result of any function call.
However, if you're using gcc then there is a function attribute warn_unused_result that you can add that causes gcc to warn if the result of a function fall is not used. Combine this with -Werror and you then have a check that results are being used.
Here's the example from the gcc info page:
int fn () __attribute__ ((warn_unused_result));
int foo ()
{
if (fn () < 0) return -1;
fn ();
return 0;
}
This will warn (or error with -Werror) about the use of fn ();.
Just writing some code to sort an array using bubble sort, but right at the start I couldn't even define an array and print it.
Code:
#include <stdio.h>
int main () {
int test[] = {9,9,9,9,9}; //define array
test[2] = 3;
bool checker = false; //is it sorted?
int i = 0;
for(int i = 0; i<=4; i++) //set random numbers for array
{
int g;
g = 4+i;
test[i] = g;
i++;
}
for (int i = 0; i <= 4; ++i ) //print array as normal
{
printf(", ", test[i]);
}
When executed it always outputs:
, , , ,
so the array is empty? or im printing it wrong? or something?
You are printing it wrong.
The line in which you are printing should read printf("%d, ", test[i]);
Also not that you have tagged the question as C++, but are using C related terms. Your #include <stdio.h> should be replaced by #include <iostream> and you should be using cout instead of printf for outputting data.
You have two problems in your code.
First, the initial 'for' loop uses 'i' as its counter variable, and your increment condition is 'i++'. That means 'i' automatically increments through each loop iteration; yet within the loop, you specify 'i++', meaning you will see the value of 'i' bumped twice with each pass. Eliminate the extraneous increment.
Second, you are printing the array incorrectly. You need to add a format qualifier such as '%d' to tell printf to use the first argument as a replacement for that specifier.
Lastly, you've indicated C++ for this code, but it really isn't. It's classic C.
I am working on a simple softmodem program. The modem is designed to implement the Audio FSK of a dial-up modem and should be able to initiate a phone call by emitting DTMF tones. Currently I am having some problems with a function which will generate sine values.
double* generate_sine( int numberOfElements, double amplitude,
double phase_in_degrees, double numberOfCycles)
{
static int i;
double *sine_output;
sine_output = malloc( numberOfElements*sizeof(double) );
for( i=0; i<numberOfElements; i++ )
{
sine_output[i] = (amplitude*sin(( (2.0*M_PI*i*numberOfCycles)/(double)numberOfElements )+
((M_PI*phase_in_degrees)/180 )));
}
return sine_output;
}
There is a segmentation error in the function. the variable "i" appears to become a pointer after the first iteration of the loop, its value is 4206692. sine_ptr also has a valid address until the second iteration of the loop at which point it become 0 (NULL).
Here is where the function is called. DEFAULT_PHASE = 0.0
int main()
{
int i;
int numElements = 10;
double* sine_ptr = generate_sine( numElements, 0.5, DEFAULT_PHASE, 440 );
for( i=0; i<numElements; i++)
{
printf( "%e \n", *(sine_ptr + i ) );
}
free(sine_ptr);
return 0;
}
After taking all of the edit suggested into consideration I was able to solve the problem in my code, thank you very much for any help that you gave me.
EDIT Added another point.
Issue Number 1
You are allocating enough memory for 5 elements (numberOfElements is 5). You are then trying to print 10 elements from the initial point. The last 5 elements will be accessing unallocated space and can result in undefined behavior. Including segmentation faults.
Issue Number 2
You are not freeing the pointer to the allocated space but a location 10 places later. This will also cause other problems if you solve the segmentation fault.
Issue Number 3
This is one of the minor ones. But sine_ptr is double, and trying to show it as int is undefined. will cause compiler warnings. Even with warnings, the numbers are downcasted. In your case the output will be all zeros. To see correct results, use %lf.
Use the following code.
int main()
{
int i;
int numElements = 5;
double* sine_ptr = generate_sine( numElements, 0.5, DEFAULT_PHASE, 440 );
for( i=0; i<numElements; i++)
{
printf( "%lf \n", *(sine_ptr + i) );
}
free(sine_ptr);
return 0;
}