Compile time error C programming Arrays - c

I wrote a small C program which takes some user input and prints it,
#include<stdio.h>
int main()
{
char name[], char add[];
short int height;
unsigned char buffer[1024];
int i,j,n,m;
printf("enter your name_length num: n is:-\n");
scanf("%d",&n);
printf("enter your name\n");
for(i=0;i<n;i++)
{
scanf("%c",&name[i]);
}
printf("enter your address: m is :-\n");
scanf("%d",&m);
for(j=0;j<n;j++)
{
scanf("%c",&add[j]);
}
printf("enter your height\n");
scanf("%d",&height);
for(i=0;i<n;i++)
{
printf("your entered name is:\t",name[i]);
}
for(j=0;j<n;j++)
{
printf("your entered address is:\t",add[i]);
}
printf("your entered height is:\n",height);
return;
}
but while running I am getting an error -
So I am at my wits end on why the array size missing is coming, is there anything that I have missed ???

There are few problems in declaration syntax.
Change this line
from
char name[], char add[];
to
char name[256], add[256];
After this you get run-time errors ( welcome to C programming )

As others have pointed out, the line char name[], char add[]; is invalid. This is because there is no way of knowing how much memory to assign to the array. There are two solutions, depending on your problem.
The best solution in this instance would be to move the declaration to below where you know the length of the user's name (assuming you're not using a strict format requiring declarations at the top):
printf("enter your name_length num: n is:-\n");
scanf("%d",&n);
char name[n];
This creates a fixed length array (of length n), and given a user's name isn't likely to change length over the course of this program this is more than acceptable.
The alternate solution is to use memory allocation, which allows you to increase or decrease the size of the array during runtime.
char *name = null;
...
printf("enter your name_length num: n is:-\n");
scanf("%d",&n);
name = malloc( n * sizeof(char));
This assigns n * sizeof(char) bytes to the array, which can later be extended, reassigned or freed. This is the more flexible option.

In C you must declare array with a constant integer like,
char name[1000], add[1000];
OR
char name[1000];
char add[1000];
OR
int size=1000;
char name[size];
char add[size];
And your main function should return integer at the end, use
return 0;

Related

program that read the names of students and put them on a array of strings that is defined by the people that are using it, isn't working

so i was doing a program in c, and the purpose of it is to read how much students are going to get their avarege grade and their names, so i have to do an array of strings with their names and so on, but the size of this array is defined by the person that is using the program, so of course the array needs to be allocated as a pointer, but how do i do that? how do i allocate the array as pointer and how do read this same array?
I made some code but i have no idea what is the error on it, because the ide doesn't show it my objective here is to know the student name add it to an array with the size specified by the user here is the program that i did:
#include<stdio.h>
#include <stdlib.h>
int main()
{
float b=0;
int op=0;
int x=0;
int i=0;
double* w;
float q=0;
int h = 0;
int p=0;
int n=0;
int no=0;
printf("enter how much students that u gonna type \n");
scanf_s("%d", &no);
char* g = (char*)malloc(no* sizeof(char));
while (n != no , n++) {
g[n] = malloc(no* sizeof(char));
printf("enter the name of the student of number %d ", n);
scanf_s("%c", & g[n]);
printf("enter how much grades u wanna type for this student\n");
scanf_s("%d", &p);
char* w = (double*)malloc(p * sizeof(double));
while ( i != p, i++)
{
w[n] = malloc(p * sizeof(char));
printf("type the %d", i);
printf("º grade\n");
scanf_s("%f", &w[i]);
}
}while(x==no,x++)
{
while (op !=p, op++)
{
b = w[op] / n;
printf("the student average is %c", g[x]);
printf(" e %f\n", & b);
}
}
return 0;
}
Step by step.
In c a string is an array of characters terminated by \0 (null char). This means its a char * that gets passed around; a pointer to the first character. This need not be dynamically allocated, but in your case it needs to be
Since you want a dynamic sized array of these you need to malloc an array of char * pointers
char *names = malloc(sizeof(char*) * no);
ie we need no char * pointers
Next we need space for each name (all we have so far are no initialized pointers)
How much space to we need? Lets choose an arbitrary buffer size say 100 chars
I would do this
.....
char name_buff[100]; // accept up to 99 chars
scanf_s("%99s", name_buff);
names[n] = strdup(name_buff);
....
this uses strdup , one of my favorite functions. It allocates memory of the correct size and then copies the string into the newly allocated slot.
Dont forget to free everything once you are done, that means loop through names freeing each entry then free names

program returning garbage values even after declaring variables in c

how do i correct this
i didn't use structure intentionally
this is a program to input student's name, subject and marks.
in the last block, the array (subject+f) 's 1st subscript is returning garbage values while the rest subscript are returning desired result.
i have also posted the image of output as link.
#include<stdio.h>
#include<string.h>
int main()
{
int size,i,k,sub,a=0,reference;
int temp,sorted;
char temp_s[10];
char temp_sb[10];
printf("enter the size of class\n");
scanf("%d",&size);
printf("how many subjects are there?\n");
scanf("%d",&sub);
reference = sub;
char name[size][20];
char subject[size*sub][20];
int marks[sub*size];
int total,subtotal,retotal;
for(k=0;k<sub;k++)
{
printf("so what's the no. %d subject\n",k+1);
scanf(" %s",(subject[k]));
}
for(i=0;i<size;i++)
{
int j,k=0;
printf("Enter a name of student %d\n",i+1);
scanf(" %s",(name+i));
for(j=a;j<reference;j++)
{
printf("enter marks of %s\n",(subject[k]));
scanf("%d",(marks+j));
k++;
}
a=j;
reference=sub+j;
}
reference=sub;
a=0;
printf("\n list of students and marks:\n");
for(i=0;i<size;i++)
{
int j,f=0;
printf("%s\n",(name+i));
for(j=a;j<reference;j++)
{
printf("%s %d\n",(subject[f]),(marks[j]));
f++;
}
a=j;
reference=sub+j;
}
}
Besides the problem with length of names and subjects, this here is a major problem:
(subject+k)
You are probably misunderstanding the subject[k] and *(subject + k) equivalent.
The variable subject is an array of arrays. That means subject[i] is an array (of char and can be used as a zero-terminated string).
The expression (subject + k) is a pointer to the array in subject[k]. It's equal to &subject[k] which have the type char (*)[10]. It's can not be used as a zero-terminated string without dereferencing. So either use *(subject + k) or the simple, less-to-write and easier-to-read subject[k].
I think you also need to change
int marks[sub];
to
int marks[size * sub];
one mark for each subject for each student, correct?

while loop asks user input one time only

#include <stdio.h>
#include <stdlib.h>
struct the_struct
{
char FirstName[20];
char LastName[32];
int Score[20];
};
int main ()
{
int i,n;
struct the_struct *ptr[100];
printf("how many students?\n");
scanf("%d",&n);
while (i<=n);
{
i==0;
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
i++;
}
}
hey guys, so when i enter the first input, it goes only once without going on for the number the user inputs, i tried the for loop but same result.
still learning C so my apology if i misunderstood something.
Thanks in advance.
Your while loop is problematic. You could rewrite it as:
for (i = 0; i < n; ++i)
{
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
}
And since you use %s to read and print Score, you should declare it as char Score[20]; instead of int.
The problem is that i is uninitialized. Therefore, the loop while (i <= n) has undefined behavior, and can end at any time.
Add int i = 0 initializer to fix this problem.
Notes:
i == 0 expression at the beginning of the loop has no effect
Since i starts at zero, your while loop should be while (i < n), not <=.
You should check the results of scanf to see if the user entered something meaningful
You should specify the size of the array into which you read a string, e.g. scanf("%31s",ptr[i]->LastName); This prevents buffer overruns.

Invalid Initializer in C

I'm a beginner in the C Programming language and I wanted to write a hashing program. I can write this program with a specified number of typedef ... Name elemenst (in an array) but, when I use dynamic allocation, an "invalid initializer" error appears.
typedef char Name[30];
Name hashTable[MAX];
int hash(Name name){
int long sum = 0;
int len=strlen(name);
int i = 0;
for (; i<len;i++)
sum += name[i];
sum = sum % MAX;
printf("\nhash of [%s] = %ld\n",name,sum);
return sum;
}
void main(){
int i,j;
for(i=0;i<MAX;i++)
strcpy(hashTable[i],"");
int pos, x, cont=1;
printf("number of names: ");
scanf("%d",&x);
while (x>=cont){
Name name = malloc(sizeof(Name)); // why this line have the error of "invalid initializer"?
printf("\ntype the %dº name: ",cont);
scanf("%s",name);
pos=hash(name);
strcpy(hashTable[pos],name);
cont++;
}
I know this answer is late, but I made a similar stupid mistake. variable Name name should be a pointer. i.e Name * name
Your declaration of name makes it statically (not dynamically) allocated. Therefore you do not need to use malloc() to allocate space.

Using an Array to print out a number of asterisks, dependent on number inputted from user in C

So this program should print out the number of asterisks dependending on the number you enter, so if you enter 5, the 5 asterisks will print out.
I don't know where I am going wrong? Also if anyone can recommend a good book for C, I read through my school text and C for dummies, I am just not getting it.
void barplot(int num1, char array[]);
int main()
{
int n1;
printf("Enter a number: ");
scanf("%d",&n1);
printf("You have entered: %d\n",n1);
char astrk[n1];
strcpy(astrk, "*");
barplot(n1, astrk);
return(0);
}
void barplot(int num1, char array[])
{
printf("num1=%d\n",num1);
int i=0;
for(i=0; i<num1; i++)
{
printf("%c",array[i]);
}
}
Edit: An array is needed per the assignment
Given that you're stuck using an array, you can fill the astrk array with '*' characters using memset:
char astrk[n1];
memset(astrk, '*', n1);
barplot(n1, astrk);
return 0;
memset fills the array (the first argument) with copies of the character (the second argument), up to the length in the third argument. Note that this doesn't null-terminate the array, so you can't directly printf it.
If you do want to be able to printf it, then you should allocate enough space for the null terminator, like so:
char astrk[n1+1];
memset(astrk, '*', n1);
astrk[n1] = '\0'
printf("%s", astrk);
return 0;
Then you don't need the barplot function at all.
You don't really need a whole char array just to store one character. Let's just replace the char[] with a single char:
void barplot(int num1, char array);
int main()
{
int n1;
printf("Enter a number: ");
scanf("%d", &n1);
printf("You have entered: %d\n", n1);
barplot(n1, '*');
return 0;
}
void barplot(int num1, char ch)
{
printf("num1=%d\n",num1);
int i;
for(i=0; i<num1; i++)
{
putchar(ch);
}
}
You did not filled your astrk array with asterisks. You just copied over a string literal that has only one asterisk.
If you need only to print these asterisks, why do you need an array at all?
try this:
void barplot(int num1)
{
printf("num1=%d\n",num1);
for(i=0; i<num1; i++)
{
printf("*");
}
printf("\n");
}
void barplot(int num1)
{
char s[BUFSIZ];
memset(s,'*',BUFSIZ);
printf("%.*s",num1%BUFSIZ,s);
}
I wonder why it has not been mentioned that standard c does not allow variable length arrays. You can do variable length arrays in C99 (ISO/IEC 9899:1999) but they are not part of C++ or standard C. It might be supported by some compilers but there is always a risk.
Besides i am certain that above question being an assignment, was given with the intention that size determined at run time should be handled using dynamic allocation such as malloc.
char arr[SIZE]; // size has to be a constant value or a variable with const modifier
Size cannot be determined at run time for the above syntax.
You should use malloc as a standard practice
char *arr = malloc(n1);
This needs to be freed latter too
free(arr);

Resources