C - Creating an array of character arrays - c

I am trying to make an array of character Arrays. The program will read in sentences and store the sentences in a character array, and then that character array will be stored in another array. After reading numerous websites and Stack Over Flow pages I think it can be done like this. The program breaks when trying to store my character array into another array, so i'm not sure how to correct my code.
#include <stdio.h>
#include <math.h>
#include <time.h>
int main(int ac, char *av[])
{
int size; //number of sentences
char strings[100];// character array to hold the sentences
char temp;
printf("Number of Strings: ");
scanf_s("%d", &size); // read in the number of sentences to type
char **c = malloc(size); //array of character arrays
int i = 0;
int j = 0;
while (i < size) //loop for number of sentences
{
printf("Enter string %i ",(i+1));
scanf_s("%c", &temp); // temp statement to clear buffer
fgets(strings, 100, stdin);
// **** this next line breaks the program
c[i][j] = strings; // store sentence into array of character arrays
j++;
i++;
}
printf("The first character in element 0 is: %d\n", c[0][0]);
system("PAUSE");
return 0;
}

Al you need to do is allocate the memory for the string just read and copy the string:
c[i][j] = strings; // replace this with:
c[i]= malloc(strlen(strings)+1);
strcpy(c[i],strings);

Sadly char **c is not array of characters arrays. But this will properly allocate a 2d array dynamically if you follow
char (*c)[SIZE];
And then doing this
c = malloc(sizeof(char[LEN][SIZE]));
Then you do what you are trying to do.
for(size_t i = 0; i < LEN; i++){
if(fgets(c[i],SIZE,stdin)){
...
}
}
Or you can do it like this
char **c = malloc(LEN);
..
for(size_t i = 0; i < LEN; i++){
c[i] = malloc(SIZE);
...
}
But again c is nothing but jagged array of characters.
Check the return value of malloc and free the dynamically allocated memory when you are done working with it.

Listen dude,
Do you want to store the words in the character array and then store this in another array.
It is what you want ?
If yes then you can do the following.
Use stdlib by using # include <stdlib.h> .
This lets you use string functions directly.
Now read every word as a string and make array of strings.
So now if you number of strings is n, define an array for that as string my_array[n] and scan each word using scanf("%s",&my_array [i]).
In this way you will get an array of strings.

Related

function to get words and put them in array

I need to write a C function that gets from the user the number of the words that he wants to enter, then the function has to scan the word from the user and but them in the array.
For example:
Program:
number of words:
User:
3
hi
my
name
(between every word there is enter) then the function has to put these words in
string array (the size of the array must be defined by malloc and the max size of the string is 100 (could be less)).
int main()
{
int n;
printf("Please enter the number of words: \n");
if (scanf("%d",&n)!=1)
return 0;
char *name;
name = malloc((sizeof(char)*100*n));
int c;
int i;
int m;
for (i = 0; i < n && ((c=getchar()) != EOF );i++)
{
name[i] = c;
}
finds_themin(&name, m); //I know this work
return 0;
}
You need to setup a pointer to pointer.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char **s;
int n;
char buffer[64];
fgets(buffer,64,stdin);
n=strtol(buffer,NULL,10);// I avoid using scanf
s=(char **)malloc(sizeof(char*)*n);// you need to declare a pointer to pointer
/*
'PtP s' would look like this:
s[0]=a char pointer so this will point to an individual string
s[1]=a char pointer so this will point to an individual string
s[2]=a char pointer so this will point to an individual string
....
so you need to allocate memory for each pointer within s.
*/
int i;
for(i=0;i<n;i++){
s[i]=(char*)malloc(sizeof(char)*100);// length of each string is 100 in this case
}
for(i=0;i<n;i++){
fgets(s[i],100,stdin);
if(strlen(s[i])>=1){// to avoid undefined behavior in case of null byte input
if(s[i][strlen(s[i])-1]=='\n'){ // fgets also puts that newline character if the string is smaller than from max length,
s[i][strlen(s[i])-1]='\0'; // just removing that newline feed from each string
}
else{
while((getchar())!='\n'); //if the string in the command line was more than 100 chars you need to remove the remaining chars for next fgets
}
}
}
for(i=0;i<n;i++){
printf("\n%s",s[i]);
}
for(i=0;i<n;i++){
free(s[i]); //avoiding leaks
}
free(s);
}
As you need to store an array of strings you need an array of char* or char** to point each string (char array).
char **name;
name = malloc(n); // to store n strings.
Then in the loop use fgets to read the input as a line. Also, you need to allocate the memory for each new char array.
fflush(stdin);
for (i = 0; i < n; i++) {
name[i] = malloc(100); // allocating memory for string.
fgets (name[i], 100, stdin); // 100 is the max len
}
You can then simply iterate over the char** array, the ith index will point to the ith string.
for (i = 0; i < n; i++) {
// printf("%s", name[i]);
}

C - how to store multiple strings in an array

Wondering how store different strings in an array.
For example a user would input 'qwe' and the program would then store that in an array variable[0]. Entering another string would then store it as variable[1] and so on
int
main(int argc, char *argv[]) {
char variable[1000];
int i;
printf("enter a variable\n");
scanf("%s", variable);
for (i = 0; ??? ;i++) {
printf("The variable entered was: %s\n",variable[i]);
}
return 0;
Im new to C so I have no idea what im doing. but thats what I have came up with so far and was wondering if I could get some help with filling in the rest
Thanks!
You can use 2D array to store multiple strings. For 10 strings each of length 100
char variable[10][100];
printf("Enter Strings\n");
for (int i = 0; i < 10 ;i++)
scanf("%100s", variable[i]);
Better to use fgets to read string.
fgets(variable[i], sizeof(variable[i]), stdin);
You can also use dynamic memory allocation by using an array of pointers to char.
The most efficient way is to have an array of character pointers and allocate memory for them as needed:
char *strings[10];
int main(int ac, char *av[]) {
memset(strings, 0, 10 * sizeof(char *));
for (int i = 0; i < 10; i += 1) {
char ins[100];
scanf("%100s", ins);
strings[i] = malloc(strlen(ins) + 1);
if (strings[i]) {
strcpy(strings[i], ins);
}
}
}
variable[0] has just stored first letter of string. If you want to store multiple strings in an array you can use 2D array.
it has structure like
arr[3][100] = { "hello","world", "there"}
and you can access them as
printf("%s", arr[0]); one by one.
scanf returns number of successful readed parameters;
use 2D array for string-array
Never go out of bounds array
#include <stdio.h>
//Use defines or constants!
#define NUM_STRINGS 10
#define MAX_LENGTH_OFSTRING 1000
int main() {
char variable[NUM_STRINGS][MAX_LENGTH_OFSTRING +1 /*for '\0' Null Character */];
int i = 0;
printf("enter a variable\n");
while(scanf("%s", variable[i]) > 0){//if you print Ctrl+Z then program finish work. Do not write more than MAX_LENGTH_OFSTRING symbols
printf("The variable entered was: %s\n",variable[i]);
i++;
if(i >= NUM_STRINGS)
break;
}
return 0;
}

append alphabet to array via a for loop in C

I'm just doing practice problems out of my C book and am stuck on this one:
Write a program that creates an array with 26 elements and stores the 26
lowercase letters in it. Also have it show the array contents.
I'm getting stuck here
char abc[26];
char index;
for(index="a", abc[0]; index<="z"; index++, abc[0]++){
abc[]=abc[index]
}
printf("%s", abc);
I'm mostly confused on how to append something to an array when its in a for loop, and how to print the entire array.
No need to append as mentioned in the comments, also be careful with char i= "a" and char i = 'a'
here is a code, that does create array of 26 lower case alphabet
#include <stdio.h>
int main()
{
char arr[27];
int i;
for(i=0; i<26; i++)
{
arr[i] = 'a'+i;
}
arr[i]='\0'; //null terminate the array
printf("%s\n", arr);
}

How to input a string in a 2d array in C?

If i want to take an input in a 2d array with each string in one row, and the next in the other(i.e. change the row on pressing enter). How can i do that in C. C doesnt seem to have convenient "String" Handling. I obviously mean doing so without the use of getchar().
3 ways are there which are mentioned below.
If you know the maximum number of strings and maximum number of chars, then you can use the below way to declare a 2D character array.
char strs[MAX_NO_OF_STRS][MAX_NO_CHARS] = {0};
for (i = 0; i < MAX_NO_OF_STRS; i++)
{
scanf("%s", strs[i]);
}
If you know the maximum number of strings, and you dont want to waste the memory by allocating memory for MAX_NO_CHARS for all strings. then go for array of char pointers.
char temp[MAX_NO_CHARS] = {0};
char *strs[MAX_NO_OF_STRS] = NULL;
for (i = 0; i < MAX_NO_OF_STRS; i++)
{
scanf("%s", temp);
strs[i] = strdup(temp);
}
If you know the maximum number of strings during run time means, you can declare a double pointer of char. Get the number of strings n from user and then allocate memory dynamically.
char temp[MAX_NO_CHARS] = {0};
char **strs = NULL;
int n = 0;
scanf("%d", &n);
strs = malloc(sizeof(char*) * n);
for (i = 0; i < n; i++)
{
scanf("%s", temp);
strs[i] = strdup(temp);
}
#include<stdio.h>
main()
{
char student_name[5][25];
int i;
for(i=0;i<5;i++)
{
printf("\nEnter a string %d: ",i+1);
scanf(" %[^\n]",student_name[i]);
}
}
u can read strings using 2d array without using getchar() by putting space in scanf(" %[^\n]")
; before %[^\n]!
An alternative to using malloc and filling up an array of pointers with buffers of a fixed size, would be to allocate a 2d array (in static storage or on the stack) and fill it up. KingsIndian modifed code example would than look like this:
#include <stdio.h>
int main()
{
char str[2][256] = {{0}};
int i = 0;
for(i=0;i<2;i++)
{
scanf("%255s", &str[i][0]);
}
return 0;
}
If all strings you expect to get are no longer than some size, than this approach will spare you the need to deal with freeing the memory yourself. It is less flexible however, meaning that you can't fit the size of an individual buffer to the string it contains.
EDIT
Adding to the information in the comment, to read a string that is terminated only by a new-line, rather than by any whitespace:
scanf("%255[^\n]", str[i]);

Finding the longest string from a list of ten strings in C?

I will have to take the input from user and find the longest input from those 10 strings..
#include<stdio.h>
#include<conio.h>
void main() {
char str[10][10]
printf("Enter strings:")
scanf("%s", str)
}
If I take the user input like this, would it store the strings in str two dimensional array? To find out the longest string first I would find the length of each strings and use max_length function to determine the longest string.
You do not need to store all of the strings, just the longest one entered so far.
Note that you do need to define a maximum length of string to avoid buffer overrun.
For example:
#define MAX_STRING_SIZE 1024
char last_entered_string[MAX_STRING_SIZE];
char longest_entered_string[MAX_STRING_SIZE] = ""; /* Must be initialized. */
scanf("%1023s", last_entered_string); /* Read one less to allow for
null terminator. */
Use a loop to accept the ten inputs and compare with the longest string. If the last entered string is longer then copy it into the longest string. As this is homework I'll not provide any further code.
No, it won't. You have to loop through and read all strings.
for(i=0;i<10;i++)
scanf("%s", str[i]);
Also, you are missing some semi-colons!
You can find the longest string put and save it for all the string received.
int main()
{
char *str = NULL;
char *compare;
printf("Enter strings:");
scanf("%s", compare);
if (strlen(str) < strlen(compare))
str = strdup(compare);
return(0);
}
And if you want to store all of users input (considering you can have just 10 string from the user)you can do this :
int main()
{
char **array;
char *str;
int x = 0;
int shortest;
array = malloc(sizeof(char*) * 10);
while (x < 10)
{
scanf("%s", str)
array[x] = strdup(str);
x++;
}
x = 0;
shortest = x;
while (x < 10)
{
if (strlen(array[x]) > strlen(shortest))
shortest = x;
x++;
}
return (0);
}
shortest will be the index of the longest string in your array.
I hope this will help you.
Store all input in an array, then do qsort() it on the array entries length and then take the first (or the last, depending on how you sorted) entry.
Ok, ok ... - this might be over-engineered ... ;-)
The program presented will take 10 input strings from the user and then finally print out the longest string and its length. It will not store any other input strings than the biggest one.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_LEN 1024
int main(int argc, char **argv){
char str_final[MAX_STR_LEN];
char str_temp[MAX_STR_LEN];
unsigned int i, j, len_str;
unsigned int num_string = 10;
unsigned int len_max = 0;
for (i=0; i<num_string; i++){
printf("Enter string number: %d\n", i);
gets(str_temp);
for (j=0; str_temp[j]; j++);
len_str = j;
if(len_str > len_max){
len_max = len_str;
memset(str_final, 0, MAX_STR_LEN);
memcpy(str_final, str_temp, len_str);
}else{
memset(str_temp, 0, MAX_STR_LEN);
}
}
printf("The biggest string is: %s\n", str_final);
printf("It's size is: %d\n", len_max);
exit(EXIT_SUCCESS);
}
I think what you can do is take a nested loop and search for a '\0' character in the row and run a counter simultaneously. as soon as you find a '\0' stop the counter and store the value of counter in a separate array . so now you will have a array of 10 integers.
Now search for smallest integer in the array and... Bingo!
The corresponding row will have the shortest string.
I know this approach is very raw but I think it will be helpful for people with only basic knowledge of C.

Resources