What is in local variables by default? - c

I have done my school assignment, and I try to fix it by the tutor's comment. However, from my tutor latest email, he points out that "It is luck if it works without making this change. With local variables, you have no idea what is in them by default." I just have no idea what the default is in my code
This is my tutor's comment:
1. The question said only local variables should be used.
The read function was supposed to read in as well as do validation of the length of the input string. Lines 14 and 15 should be inside the read function, not in main.
Because you used text as a global variable, you have been able to write your functions without the need for the string parameters s, st and str. The whole point of this assignment was to test your ability to program with string parameters. While your functions appear to have string parameters, they might as well not be there with text global and only text in the code inside the functions. The read function should be written in terms of s, not text. The count function should be written in terms of st, not text. The justify function should be have str wherever you have text. You have not shown that you understand how string parameters are used.
#include<stdio.h>
#include<string.h>
void read(), justify(char *str, int g);
int count(char *st);
int main(){
char text[100];
int gaps, i;
gaps = 0;
for(i=0; i<3; i++) {
read(text);
gaps = count(text);
justify(text, gaps);
printf("\n");
}
}
void read(char *s){
int length;
printf("Enter a line of text: ");
gets(s);
length = strlen(s);
while(length!=0){
if(length<46){
printf("123456789012345678901234567890123456789012345\n");
length = 0;
} else {
printf("Enter a line of text: ");
gets(s);
length = strlen(s);
}
}
}
int count(char *st){
int num, i, num2;
num = 0;
num2 = strlen(st);
for(i=0; i<num2; i++){
if(st[i]==' '){
num++;
}
}
return num;
}
void justify(char *str, int g){
int i, j, num, m, n, temp;
temp = strlen(str);
num = 45 - temp;
m = num / g;
n = num % g;
for(i=0; i<temp; i++){
printf("%c", str[i]);
if(str[i]==' '){
for(j=0; j<m; j++){
printf(" ");
}
if(n!=0){
printf(" ");
n--;
}
}
}
printf("\n");
}
I would like to learn how to improve the code and make it work without luck. Cheers!

Regarding the title, “What is in local variables by default?”
Nothing. Per C 2018 6.7.9 10, “If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.” (What you think of as a “local variable” is an object with automatic storage duration.) Per 3.19.2, an indeterminate value is either an unspecified value or a trap representation. Per 3.19.3, the C standard imposes no requirements on which value is chosen in any instance.
Consider:
int x;
printf("%d", x);
printf("%d", x);
In these two instances, the printf may print different numbers. The value of x is unspecified in any instance. The program is broken.
Furthermore, there is a rule in 6.3.2.1 2 that amounts to: If you use an uninitialized local variable and its address has never been taken, the behavior of the program is not defined by the C standard. This means, not only can the variable appear to have different values at different times, but that the C standard does not define the behavior of the program at all. The printf statement will not necessarily print. The program could crash. The program could call entirely different routines from what you expect. The C standard imposes no requirements.
Solution: Initialize your local variables by writing = SomeInitialValue when declaring them, as in int x = 0;, or by assigning them values before using them.
1. The question said only local variables should be used.
Solution: Use only local variables. Remove global variables from your program. If a routine needs data from a caller, pass it with a parameter.
2. The read function was supposed to read… Lines 14 and 15…
Lines 14 and 15 in the code in your question do not appear to correspond to lines that should be in the read function. You appear to have put code in the question that differs from what the tutor was referring to.
Solution: Put exactly the code the tutor reviewed in the question. Follow the tutor’s instructions.
3. Because you used text as a global variable…
See both 1. and 2. above. As with 2., the code does not match this comment; you appear to have shown different code from what the tutor reviewed. Show the exact code in the question, and do not use global variables.

Related

How to find the total number of a certain element in an array(C)

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)

in C char foo[foo] is not allowed, but why? and how to use input as declaration for this [foo]

I am new in C and I am used to zx basic and z80 asm. I want to use the value of an input to make a character array but
int amount_of_dice_sides ;
printf("Give number of sides of dice:\n") ;
scanf("%d", &amount_of_dice_sides) ;
char all[amount_of_dice_sides] ;
is not allowed yet
int amount_of_dice_sides=6 ;
char all[6] ;
works very fine.... how do i get that
char all[amount_of_dice_sides] ;
working?
its a very primer question, very 'basic' but i seem not to find an answer that does NOT start with 'the difference between const char*foo '
which has nothing to do with setting a char with an integer but only as a real value instead of a variable.
i found these possible 'char foo' but none is what i waht to achieve
https://medium.com/#bartobri/untangling-complex-c-declarations-9b6a0cf88c96
EDIT
i use another compiler then gcc
#include <stdio.h>
void main ()
{
int amount_of_dice_sides ;
printf("Give number of sides of dice:\n") ;
scanf("%d", &amount_of_dice_sides) ;
char all[amount_of_dice_sides] ;
return ;
}
works fine but not with zcc.
so i have to look at another place, and i am realy still learning.
see ya , and thanks for a load off immidiate answers. chris
The reason why it isn't working is that you are using a compiler and MCU from the Jurassic period. Variable-length arrays (VLA) were introduced in the C language in the year 1999. Z80 might be a nice platform to learn one flavour of assembler, but it's a horrible platform for learning C.
But regardless, you should never use VLA allocation nor heap allocation on low end microcontrollers, because they have very limited memory in general and stack memory in particular. (And heap allocation simply doesn't make sense.)
For the same reasons, you shouldn't be using stdio.h either, it will kill a significant amount of all available memory. Instead you should use the raw UART driver or write one yourself - assuming the stdio.h functions go to a terminal on a PC. Start by finding the linker map file, study it and see how much memory these libs actually take, then you'll see for yourself why they aren't suitable.
C only allows variable length stack arrays in certain situations. Specifically when you have a function, you can use a calculation based on a parameter to have a stack allocated array.
void func(int param){
int array[param] // call it here
// do some work with array as a scratch space
} // when the final curly bracket is called, the array is destroyed
However, this technique can easily get you into trouble. If you don't specify the length of an array, and a user enters a really big number, then you get a Stack Overflow. On early C compilers and platforms (like the Intel-8051), this was painfully common, as well as calling too many nested functions.
The solution is to allocate your variable length arrays on the heap. Some platforms do allow allocation to the stack as well, but not all of them.
// In sumfunc we roll a number of dice, print, and return the sum
// Malloc allocates to the heap
int sumFunc_malloc(int num_dice){
int * dice = (int*)malloc(sizeof(int) * num_dice); // our allocation
int sum = 0;
for (int i = 0; i < num_dice; i++){
dice[i] = (rand() % 6) + 1;
printf("Dice %d rolled a %d", i, dice[i];
sum += dice[i];
}
free(dice); // REQUIRED or memory will leak, and eventually program will fail
return sum;
}
// In sumfunc we roll a number of dice, print, and return the sum
// Alloca is not supported by all platforms, but is on the stack
int sumFunc_alloca(int num_dice){
int * dice = (int*)alloca(sizeof(int) * num_dice); // our allocation on the stack
int sum = 0;
for (int i = 0; i < num_dice; i++){
dice[i] = (rand() % 6) + 1;
printf("Dice %d rolled a %d", i, dice[i];
sum += dice[i];
}
return sum;
}
One final alternative, especially on devices like the 8051 is to have a scratchpad that you do large work in, and simply reusing it.
static char scratch[100];
int func(int param){
// use scratch to hold lots of temporary values
}
The best comment was explaining the WHY part: that compiling will set memory at a permanent location and if i change that size later C will get in trouble with allocated variables.
Meanwhile i do indeed learn C on a dinosar called z88dk. And it took some time befoe i was able to use it. z88dk is in a slow rewrite from 'classic' to SDCC and others aswell.
this one works in zcc but with BUILD_SCC=1 while building z88dk itself (!!!) and using a special lib for zx spectrum:
/* C source start */
/* by chris born ad 2020 as homework for z88dk, farkle */
/* zcc +zx -vn -startup=0 -clib=sdcc_iy dice_026.c -o dice026 -create-app */
#include <arch/zx.h>
#include <stdio.h>
#include <stdlib.h>
int dice(int aods)
{
char d ;
/*srand (seedrandom); */
d =+ rand()%aods ;
return d;
}
int main()
{
int x , amount_of_dice_sides , hand_of_dice ;
char number , hand[256] ;
zx_cls(PAPER_WHITE) ;
printf("Give number of sides of dice:\n") ;
scanf("%d", &amount_of_dice_sides) ;
printf("how many dice do you want:\n") ;
scanf("%d", &hand_of_dice) ;
printf(" amount of dice %d ",hand_of_dice );
if (hand_of_dice > 255)
{
hand_of_dice = 255 ;
printf(" is now %d", hand_of_dice) ;
}
printf("\n") ;
scanf("press a key") ;
/* char hand[&hand_of_dice]; */ /* int is max 65536 gives a huge hand filled with stones */
printf("You threw: \n");
for (x=1 ; x<=hand_of_dice ;x++)
{
number=dice(amount_of_dice_sides);
printf("stone %d : %d \n",x , number);
hand[x]=number;
}
printf("\n");
return 0;
}
/* C source end */
so why do i got stuck here?
well its the only source i realy have!
In this declaration,
int amount_of_dice_sides ;
printf("Give number of sides of dice:\n") ;
scanf("%d", &amount_of_dice_sides) ;
char all[amount_of_dice_sides] ;
all[amount_of_dice_sides] is a static array & it's size needs to known to compiler prior building the code.
What happens in your case is size of array is being read as input from user which happens after compilation
It's always recommended to explicitly mention the size of array to avoid memory issues in code later

function declaration and call and definition in c

Why is this code not running after printing of array if I take value of n>=9?
#include <stdio.h>
#include <math.h>
float mean_function(float array[],int n);
int main() {
int i,n;
float array[n],mean,sum=0,s2,summation,deno,C[i],elements;
printf("Enter No of Elements\n");
scanf("%d",&n);
printf("Enter Elements\n");
for(i=0;i<n;i++){
scanf("%f",&array[i]);
printf("%f",array[i]);
}
printf("sample variance(s2) : (sum((x-mean)*(x-mean)))/(n-1) /n");
printf("population variance(sigma2) : (sum((x-u)*(x-u))/n");
mean_function(array,n);
for(i=0;i<n;i++) {
deno=((array[i]-mean)*(array[i]-mean));
C[i]=deno;
summation=summation+C[i];
}
s2=((summation)/(n-1));
printf("s2=%f \n",s2);
}
float mean_function(float array[],int n) {
int i;
float sum=0,mean;
for(i=0;i<n;i++){ sum=sum+array[i]; }
mean=(sum/n);
return mean;
}
Why is this code not running after printing of array if I take value
of n>=9?
Some thoughts about your code (and about building programs in steps):
Arrays in C don't change in size once defined. VLAs are out for a variety of reasons. malloc() is in.
Use double, unless there is a specific reason to use floats.
Define and initialize one variable per line. Uninit vars can only result in an error as mentioned by #Jens.
Function declarations at the top (which you have done)
During development, there is no need to complicate things with a scanf (at least initially). It only adds an unwarranted layer of complexity. If you are testing statistical functions (mean, variance), put numbers in a pre-defined static array and verify functionality first.
C[i] as been declared with uninitialized i.
For this initial phase of building this program, I include a basic program.
I am not a fan of zero space between tokens (but ignore that)
Consider calling your array something other than 'array'.
Calculating the size of the samples array allows you to change the number of elements without changing anything else in code; which adds another layer of complexity to an already difficult phase.
#include <stdio.h>
#include <math.h>
double sample_mean(double* p, int n);
int main()
{
double samples[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 16.5, 2.3};
double mean = 0.0;
int size_samples = sizeof samples/sizeof(double);
printf("size_samples = %d\n", size_samples);
mean = sample_mean(samples, size_samples);
printf("Mean = %.2lf", mean);
}
// -------------------------------
double sample_mean(double* p, int n)
{
double mean = 0.0;
double total = 0.0;
for(int i = 0; i < n; i++)
total += *p++;
mean = total/n;
return mean;
}
Once this functionality is present (saved), you can start working on other stat functions. This way you can work step by step to get closer to the desired outcome.
Next up you can define sample_variance(double* p, int n) and work on that knowing that additional(new errors) are not coming from your code written so far.
Output:
size_samples = 8
Mean = 5.24
I hope it helps.
The code is likely not running because array[n] is declared with an uninitialized n. At the time you read n with scanf(), the array does not automatically "grow into the right size". You should either declare array big enough, or if you really want it to be user-defined, use malloc to allocate it (read the comp.lang.c FAQ) and all Stackoverflow questions tagged array...)
In addition, the scanf at some point fails. Note that when you enter numbers, you also have the "Enter" as a newline ('\n') in the input stream. You never read the newline so the next scanf fails.
This becomes obvious when you actually check the return value from scanf with code like this:
if (scanf("%f", &array[i]) == 1) {
/* successfully converted 1 item */
}
else {
/* scanf failed */
}
Usually what you want is to skip whitespace in the input. You do this by placing a space in the scanf format. Note that a single space tells scanf to skip any amount of white-space.
if (scanf(" %f", &array[i]) == 1) {

Summing an Array of Numbers but Receiving Error when Run [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to sum an array of numbers. The array has a length determined by an input and then the user gives the array. There were no compilation errors and I am able to run other programs. On the immediate start of running the program I am given a message that program has stopped working and that windows is searching for solution.
#include <stdio.h>
int main()
{
int sum, length, count;
int array[length];
sum=0;
scanf("%d",&length);
scanf("%d",&sum);
for(count=0; count<length-1; count++)
{
sum = sum + array[count];
}
printf("%d", sum);
return 0;
}
When you declare your array it depends on length but you ask the user for length after.
A solution could be to ask the user for length (scanf("%d",&length);) before declaring your actual array (int array[length];).
you should move int array[length] to after scanf("%d", &length). But it is not allowed in C to declare variables after the first non-declaration (it is however possible if you compile this program as C++).
In fact, in standard C you can't have a non-const length definition for an array variable. gcc on the other hand for example allows this nevertheless.
In your case, the problem is that length has an undefined value at the declaration of int array[length];. If you are lucky, your data segment has been initialized to zero (there is no guarantee for that) but otherwise, it may be any value, including a value which leads the program to exceed your physical memory.
A more standard way of doing this is:
int *array = NULL;
scanf("%d",&length);
...
array = (int*) malloc(sizeof(int) * length);
...
free(array);
By the way, even after fixing that, you will most likely get random numbers because you never actually assign the contents of the elements of array.
Local variable are initialized to 0. Hence value of length is 0. So you array is of length. You are then reading length, say 10, from stdin and expect the array to be of length 10. This can't be. Since this is a stack variable, the size is determined in time of pre-processing and not in run time. If you want to define the array length in run time then use malloc.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int sum, length, count;
int *array;
sum=0;
scanf("%d", &length);
scanf("%d",&sum);
array = (int *)malloc(sizeof(int) * length);
if (array == NULL) return 0;
memset(array, length, 0);
for(count=0; count<length-1; count++)
{
sum = sum + array[count];
}
printf("%d", sum);
return 0;
}
Thanks.
first problem:
the length variable is being used to set the number of entries in the array[], before the variable length is set. Therefore, length will contain what ever trash happens to be on the stack when the program starts so the number of entries defined in array[] is an unknown.
This results in undefined behaviour and could lead to a seg fault event, depending on what was on the stack and what the user entered for length.
second problem:
The array array[] is never initialized so will contain what ever trash is on the stack at program startup. This means the value being printed could be anything. And the 'sum' could overflow, depending on the trash values in array[]
OP program lacks the part of data input, it's asking for sum instead of the values to sum, which is weird. The only inputs requested are also never checked (the return value of scanf must always be checked).
In C (at least C99 and optionally C11) Variable Length Arrays, like the one defined by int array[length], can be used, but the variable length here is used uninitialized and before it is even asked to the user.
Moreover, the loop where the sum is calculated stops before the last element of the array (not really a big deal in this case, considering that all those variables are uninitialized...).
A better way to perform this task could be this:
#include <stdio.h>
// helper function to read an integer from stdin
int read_int( int *value ) {
int ret = 0;
while ( (ret = scanf("%d", value)) != 1 ) {
if ( ret == EOF ) {
printf("Error: Unexpected end of input.\n");
break;
}
scanf("%*[^\n]"); // ignore the rest of the line
printf("Please, enter a number!\n");
}
return ret;
}
int main(void) {
int sum = 0,
length = 0,
count,
i;
printf("Please, enter the number of values you want to add: ");
if ( read_int(&length) == EOF )
return -1;
// Use a VLA to store the numbers
int array[length];
// input the values
for ( count = 0; count < length; ++count ) {
// please, note ^^^^^^^^ the range check
printf("Value n° %2d: ", count + 1);
if ( read_int(&array[count]) == EOF ) {
printf("Warning: You entered only %d values out of %d.\n",
count, length);
break;
}
// you can sum the values right here, without using an array...
}
// sum the values in the array
for ( i = 0; i < count; ++i ) {
// ^^^^^^^^^ sum only the inputted values
sum += array[i];
}
printf("The sum of the values is:\n%d\n", sum);
return 0;
}

How can i add numbers to an array using scan f

I want to add numbers to an array using scanf
What did i do wrong? it says expected an expression on the first bracket { in front of i inside the scanf...
void addScores(int a[],int *counter){
int i=0;
printf("please enter your score..");
scanf_s("%i", a[*c] = {i});
}//end add scores
I suggest:
void addScores(int *a, int count){
int i;
for(i = 0; i < count; i++) {
printf("please enter your score..");
scanf("%d", a+i);
}
}
Usage:
int main() {
int scores[6];
addScores(scores, 6);
}
a+i is not friendly to newcomer.
I suggest
scanf("%d", &a[i]);
Your code suggests that you expect that your array will be dynamically resized; but that's not what happens in C. You have to create an array of the right size upfront. Assuming that you allocated enough memory in your array for all the scores you might want to collect, the following would work:
#include <stdio.h>
int addScores(int *a, int *count) {
return scanf("%d", &a[(*count)++]);
}
int main(void) {
int scores[100];
int sCount = 0;
int sumScore = 0;
printf("enter scores followed by <return>. To finish, type Q\n");
while(addScores(scores, &sCount)>0 && sCount < 100);
printf("total number of scores entered: %d\n", --sCount);
while(sCount >= 0) sumScore += scores[sCount--];
printf("The total score is %d\n", sumScore);
}
A few things to note:
The function addScores doesn't keep track of the total count: that variable is kept in the main program
A simple mechanism for end-of-input: if a letter is entered, scanf will not find a number and return a value of 0
Simple prompts to tell the user what to do are always an essential part of any program - even a simple five-liner.
There are more compact ways of writing certain expressions in the above - but in my experience, clarity ALWAYS trumps cleverness - and the compiler will typically optimize out any apparent redundancy. Thus - don't be afraid of extra parentheses to make sure you will get what you intended.
If you do need to dynamically increase the size of your array, look at realloc. It can be used in conjunction with malloc to create arrays of variable size. But it won't work if your initial array is declared as in the above code snippet.
Testing for a return value (of addScores, and thus effectively of scanf) >0 rather than !=0 catches the case where someone types ctrl-D ("EOF") to terminate input. Thanks #chux for the suggestion!

Resources