Can someone tell me whats wrong with that code?And i cant use malloc because i havent learn it in class.I mean can i make a 2d array of strings without malloc and if yes how i am i supposed to write an element when i want to change it/print it/scan it.Thanks in advance
int main() {
size_t x,y;
char *a[50][7];
for(x=0;x<=SIZEX;x++)
{
printf("\nPlease enter the name of the new user\n");
scanf(" %s",a[x][0]);
printf("Please enter the surname of the new user\n");
scanf(" %s",a[x][1]);
printf("Please enter the Identity Number of the new user\n");
scanf(" %s",a[x][2]);
printf("Please enter the year of birth of the new user\n");
scanf(" %s",a[x][3]);
printf("Please enter the username of the new user\n");
scanf(" %s",a[x][4]);
}
return 0;
}
So, you need a 2d array of strings (char arrays). One way to achieve this would be to allocate a 3d array of char as:
char x[50][7][MAX_LENGTH];
You can think as having a matrix of array start (of pointers) and then, another dimension to give depth to your matrix (i.e. storage space for your string).
Your approach is also fine, as long as you are willing to allocate manually using malloc or similar storage space for your strings.
can i make a 2d array of strings without malloc
Sure. Let's reduce this to 2*3:
#include <stdio.h>
char * pa[2][3] = {
{"a", "bb","ccc"},
{"dddd", "eeeee", "ffffff"}
};
int main(void)
{
for (size_t i = 0; i < 2; ++i)
{
for (size_t j = 0; j < 3; ++j)
{
printf("i=%zu, j=%zu: string='%s'\n", i, j, pa[i][j]);
}
}
}
Output:
i=0, j=0: string='a'
i=0 j=1: string='bb'
i=0, j=2: string='ccc'
i=1, j=0: string='dddd'
i=1, j=1: string='eeeee'
i=1, j=2: string='ffffff'
Related
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
I'm trying to build a program that has a student id array, a course code array of char pointers to string literals, and a registration table 2d array to hold a 1 or 0 whether the student is enrolled in a course or not. So far I am at the point where I am adding the students which works fine. The program also runs as expected when I input a total of 1 course. The issue however is when I try to add more than 1 course code to the courseArray, I'm getting a segmentation error after inputting the codes. I'm unsure how to fix this and no resource on the matter seems to point me in the right direction. Any help with this is appreciated.
#include <stdio.h>
#include "Functions.h"
#include <stdbool.h>
int main()
{
//declaring variables for number of students and courses
int numStudents, numCourses;
//declaring 2d array for the registration table
int registrationTable[numStudents][numCourses];
//prompting user input for number of students and storing in numStudents
printf("How many students would you like to register: \n");
scanf("%d", &numStudents);
//create student array based on numStudents
int studentArray[numStudents];
//Prompting user input for id's of students in student array
for (int i = 0; i < numStudents; i++)
{
printf("Please enter the student ID for student %d: \n", i + 1);
scanf("%d", &studentArray[i]);
}
//Prompting user input for number of courses offered and storing in numCourses
printf("How many courses are you offering: \n");
scanf("%d", &numCourses);
//create couses array based on numCouses
char *courseArray[numCourses];
//Prompting user input for course codes in course array
for (int i = 0; i < numCourses; i++)
{
printf("Please enter the course code for course %d: \n", i + 1);
scanf(" %s", courseArray[i]);
}
validate(studentArray, courseArray, numStudents, numCourses);
return 0;
}
When you declare the registrationTable array, numStudents and numCourses are uninitialized. This invokes undefined behavior.
Using scanf later to read values into these variables does not alter the declaration of the array.
However, it doesn't appear you use this array, so this is not causing your segmentation fault.
Your problem stems from:
char *courseArray[numCourses];
And then reading into that array of strings.
for (int i = 0; i < numCourses; i++)
{
printf("Please enter the course code for course %d: \n", i + 1);
scanf(" %s", courseArray[i]);
}
You have declared an array of char pointers, but these pointers do not themselves point to anything. You would either need to use a 2-dimensional array instead like char courseArray[numCourses][100] or use malloc to dynamically allocate the memory for each pointer to point to.
Should you choose to use malloc, you will need to remember to free each string in the array as well.
Hello I am trying to make a program that lets the user input the size of the array.
I am stuck on making my array sized based on the user. This is what I have so far
void main(void)
{
const int size = 0;
int aval[size], i;
printf("Please enter the size of the array: ");
scanf("%i", &size);
printf("\n\nPlease enter array values:\n");
for (i = 0; i < size; i++)
{
scanf("%i", &aval[i]);
}
while (!_kbhit());
}
Better way would be:
int size = 0;
int *aval;
printf("Please enter the size of the array: ");
scanf("%i", &size);
/* Should verify size is reasonable here */
aval = malloc(size * sizeof(*aval));
printf("\n\nPlease enter array values:\n");
for (i = 0; i < size; i++)
{
scanf("%i", &aval[i]);
}
Doing it this way creates the array in the proper data area, rather than in the local automatic area, which may have limited size. Also, if you are done with the array before the end of the program, then you can free it to recover the space.
You initialize size with 0 and then create an array of the size of size, which is 0. Later size is changed, but that is not entangled to your array. Try this:
//Something before
const int size = 0;
printf("Please enter the size of the array: ");
scanf("%i", &size);
int aval[size], i;
//Something after
#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.
Help me to get out of this problem. I'm using GCC on ubuntu12.04. While I write this program to get 5 strings from keyboard n then print these strings on screen. Program is compiled but during execution it takes strings from keyboard but print only last string. The program which I have written is below:
void main()
{
char names[10];
int i,j;
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%s",names);
}
for(i=0;i<5;i++)
printf(" the names you enter are %s\n", names);
}
1) you can use 2D char array in this way
char names[5][100];
each line in the 2D array is an array of char with size = 100
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%99s",names[i]);
}
2) You can use array of pointers in this way
char *names[5];
each element in the array is a pointer to a string (char array). you have to assign each pointer in the array to a memory space before you call scanf()
for(i=0;i<5;i++)
{
names[i]=malloc(100);
printf(" Enter a name which you want to register\n");
scanf("%99s",names[i]);
}
3) if you compile with gcc version >2.7 then your scanf() can allocate memory by using "%ms" instead of "%s"
char *names[5];
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%ms",&names[i]);
}
There is a simple example about reading and keeping string in the char array.
#include <stdio.h>
const int MACRO = 6;
int main() {
printf("Hello Admin Please Enter the Items:\n");
char items[MACRO][20];
for (int i = 0; i < MACRO; ++i) {
scanf("%19s", items[i]);
}
for (int i = 0; i < MACRO; ++i) {
printf("%s ", items[i]);
}
return 0;
}
In your program the mistake is that you have not putted '&'address of operator int the first for loop . names in your case is an array if you store %s string in names and not &names[0] or &names[1] or so on then as array itself acts as a pointer therefore the array "names" is pointing to the address of its first elements i.e. names[0] . so if you are writing scanf("%s",names); that is similar to scanf("%s",&names[0]); so as you are storing the names in one element only and that too for 5 iterations for only the last string you have entered will be stored and previous strings will be gone . so onlye last string is printed in your program .
in your code, you only declare char data type to be one dimensional and thus it will always overwrite the previous input,that's why the result is the last input printed 5 times.
char names[10];
the above declaration means that you declare a char type variable only with 10 character size without an extra array,it means you only declare a single variable for 5 input.
to make a two dimensional char, you will need to declare it like this :
char names[5][10];
in the code above, it means that you declare a char type variable with 10 character size in an array of 5.
Here is the code I wrote using pointer.
#include <stdio.h>
void main()
{
char *string[100];
int ln;
printf("Enter numbar of lines: ");
scanf("%d",&ln);
printf("\n");
for(int x=0;x<ln;x++)
{
printf("Enter line no - %d ",(x+1));
scanf("%ms",&string[x]); // I am using gcc to compile file, that's why using %ms to allocate memory.
}
printf("\n\n");
for(int x=0;x<ln;x++)
{
printf("Line No %d - %s \n",(x+1),string[x]);
}
}
Another code using two dimensional Array
#include <stdio.h>
void main()
{
int ln;
printf("Enter numbar of lines: ");
scanf("%d",&ln);
printf("\n");
char string[ln][10];
for(int x=0;x<ln;x++){
printf("Enter line no - %d ",(x+1));
scanf("%s",&string[x][0]);
}
for(int x=0;x<ln;x++)
{
printf("Line No %d - %s \n",(x+1),string[x]);
}
}