C numeric code validator - c

I'm new to C and programming in general, so I've studied a bit and wanted to make a simple program that validates personal numeric codes from my country. This is the program:
#include <stdio.h>
int validateCNP(char cnp[13]);
int main(int argc, const char * argv[])
{
char cnp[13];
printf("Introduceti CNP-ul:\n");
scanf("%s", cnp);
if(validateCNP(&cnp[0]) == 1) {
printf("CNP valid");
} else {
printf("CNP invalid");
}
return 0;
}
int validateCNP(char cnp[13]) {
char verif[13];
int intVerif[12], intCnp[13];
int i, checksum = 0;
strcpy(&verif[0], "279146358279");
for (i = 0; i<11; i++){
intVerif[i] = (unsigned)verif[i] - 48;
}
for (i=0; i<12; i++) {
intCnp[i] = cnp[i] - 48;
}
for (i=0; i<11; i++) {
checksum += intCnp[i] * intVerif[i];
}
checksum %= 11;
if (checksum == intCnp[12]) {
return 1;
} else {
return 0;
}
}
Sample output
Introduceti CNP-ul:
1650116398203
(lldb)
It also seems that when it converts strings to int arrays, it screws up the last element
Printing description of intVerif:
(int [12]) intVerif = {
[0] = 2
[1] = 7
[2] = 9
[3] = 1
[4] = 4
[5] = 6
[6] = 3
[7] = 5
[8] = 8
[9] = 2
[10] = 7
[11] = 32767
}
Printing description of intCnp:
(int [13]) intCnp = {
[0] = 1
[1] = 6
[2] = 5
[3] = 0
[4] = 1
[5] = 1
[6] = 6
[7] = 3
[8] = 9
[9] = 8
[10] = 2
[11] = 0
[12] = 0
}
Could someone point out what I'm doing wrong, I've tried different approaches, none seemed to work.

Your basic error was already pointed out by MadHatter: Your loops omit the last entry.
Another error is in main: The CNP is 13 characters long, so your cnp array must have at least 14 characters - you have to provide space for the terminating null character '\0'. You should also limit the length of the characters to read in oder to avoid buffer overflow:
scanf("%13s", cnp);
Here, the thirteen means that at most 13 characters (plus the terminating null character) are read.
It is a good idea to check whether your string actually has 13 digits, so that you don't process garbage characters. And you've forgotten to cater for the case where the remainder is 10 - in which case the check digit is 1.

You loop goes from 0 to 10:
for (i = 0; i<11; i++){
intVerif[i] = (unsigned)verif[i] - 48;
}
You are never writing intVerif[11] so it contains garbage.
Similar problem in intCnp[] also.
EDIT : (On OP's Comment)
Looks like your input:"1650116398203" is 13 letters long whereas your cnp array needs one extra space for \0 character. Therfore your input is causing array-out-of-bounds which leads to the undefined behavior.

Related

Generate histogram in c

I am stuck with creating this histogram in C. The thing is that the assignment is to count how often every user input occurs.
For: 1 0 6 1 5 0 7 9 0 7 --> there is 3x 0, 2x 1, etc.
Then, the occurrence has to be converted to stars instead of the number of occurrences. I think I covered the 1st and 3rd steps, but I struggle with converting the number to stars. Do I have to make a new loop, or do I use the current nested loops? I will be forever grateful to whoever can provide me some insights.
So my exercise is:
Ask the user input and store in an array
Process the array and generate the histogram array
Display the histogram as stars
My code
#include <stdio.h>
void printHistogram ( int *hist, int n );
int main() {
int i, j;
int inputValue;
printf("Input the amount of values: \n");
scanf("%d", &inputValue);
int hist[inputValue];
printf("Input the values between 0 and 9 (separated by space): \n");
for (i = 0; i < inputValue; ++i) {
scanf("%d", &hist[i]);
}
int results[10] = {0};
// Processing data to compute histogram, see 5.17
for (i = 0; i < 10; ++i) {
for(j = 0; j < inputValue; j++) {
if ( hist[j] == i){
results[i]++;
}
}
}
printf("\n");
printHistogram(hist, 10);
return 0;
}
void printHistogram(int *hist, int n) {
int i, j;
for (i = 0; i < n; i++) {
printf("[%d] ", i);
for ( j = 0; j < hist[i]; ++j) {
printf("*");
}
printf("\n");
}
}
Input
10
1 0 6 1 5 0 7 9 0 7
Output
Input the amount of values:
Input the values between 0 and 9 (separated by space):
[0] *
[1]
[2] ******
[3] *
[4] *****
[5]
[6] *******
[7] *********
[8]
[9] *******
Output should be:
Input the amount of values: 10
Input the values between 0 and 9 (separated by space):
[0] ***
[1] **
[2]
[3]
[4]
[5] *
[6] *
[7] **
[8]
[9] *
As #rafix07 commented, you just have to call printHistogram(results, 10) instead of printHistogram(hist, 10).
Already compiled and tested... works

strings to array and locating a character in a string

i am working on a program where the input is an ID of 9 numbers :
program checks if the id is correct or not by :-
checking if the string is formed by numbers only .
every number has a weight of 1 or 2 so it should be 1 2 1 2 1 2 1 2
1
multiply the weight and the number
if the number is bigger than 9 then add the numbers forming it .
if the number is from multiplication of 10 then the ID is correct ..
example :-
1 7 9 3 7 9 2 5 0-ID
1 2 1 2 1 2 1 2 1-Weight
1 14 9 6 7 18 2 10 0-num x weight
1 5 9 6 7 9 2 1 0-(4)
sum = 40 then it is a correct ID.
I wrote most of it but then i noticed that it has to be a string . so my questions are :
is there a way to put a string into an array?as doing it with an
array is way easier.
how do i locate a place in a string ? like if i want the third
character in a string how do i locate it?.
and here is the code that i did it does not work yet and it needs alot of changes but i guess i will put it anyways :-
#include<stdio.h>
#define N 9
void input(int num[N]);
int check(int num[N]);
int main()
{
int num[N],a;
input(num);
a = check(num);
if (a = 1)
printf("ID is correct");
else printf("ID is NOT correct");
}
void input(int num[N])
{
int i;
printf("Enter your ID (9digits) :-");
for (i = 0;i < N;i++)
scanf("%d",num[i]);
}
int check(int num[N])
{
int w[N] = { 1,2,1,2,1,2,1,2,1 },wxnum[N],i,tota[N],sum,g;
for (i = 0;i < N;i++)
wxnum[i] = num[i] * w[i];
for (i = 0;i < N;i++)
{
if (wxnum[i] > 9)
tota[i] = wxnum[i] / 10 + wxnum[i] % 10;
else tota[i] = wxnum[i];
}
sum = tota[0] + tota[1] + tota[2] + tota[3] + tota[4] + tota[5] + tota[6] + tota[7] + tota[8];
g = sum % 10;
if (g = 0)
return 1;
else
return 0;
}
Thanks everyone for your help.
You can get a string by doing
/*N is defined as 9 in your code.*/
/*Considering there is always a '\0' in every string, we should allocat N + 1 slot for your nine numbers and the extra '\0'.*/
char chStr[N + 1];
scanf("%s", chStr);
After you got the string, you can take advantage of the values of charactor '0' - '9' (their values are from 48 to 57 correspondingly) in ASCII table, and easily transfer the charactors into integers by doing:
int i = 0;
for (i = 0; i < N; i++)
{
chStr[i] = chStr[i] - '0';
}
If you are restrict on the type, you can transfer these char values into int values by adding extra two lines:
int num[N];
int i = 0;
for (i = 0; i < N; i++)
{
chStr[i] = chStr[i] - '0';
num[i] = (int) chStr[i];
}
Please note that my code didn't check the validation of user input. To make it more secure, you can use
scanf("%9s", chStr);
to declare the maximum length that the user can input.

Count alphabets in C using log functions(without math.h) and arrays

I'm facing a slight problem with one of my projects. I am supposed to write a c program to calculate each character present in the input/file. (It's supposed to be a basic program.) The constraints - I cannot use the math.h library to produce log functions and obtain an output in the format:
1
5 1 2 0 2 2 5 8 4 3 6 6 2 5 5 7 2 1 1 2
7 9 8 1 7 2 4 1 0 0 4 5 0 2 2 5 2 6 3 6 6 3 7 0 2 2
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
The program is supposed to count the number of occurrences of each alphabetic letter (case insensitive) in the stdin input stream and display a histogram.
As you can see, the output is formatted vertically with each line printing the base 10 number of the position of the character.
Now, this might seem silly, but what I have so far is this:
#include <stdio.h>
#include <ctype.h>
/*
int logBase10 (int num) {
method to calculate the log base 10 of num
}
*/
int main (int argc, char * argv[]) {
char alpha;
int count = 0;
int ascii[128] = {0};
while ( (alpha = getchar()) != EOF) {
count++;
ascii[(int)alpha]++;
alpha = getchar();
}
printf("Char \t Count \n");
printf("------------------------\n");
for (int i = 0; i < 127; i++) {
if(ascii[i] > 0) {
printf("%c \t %d \n", i, ascii[i]);
}
}
}
Which produces an output like this:
Char Count
------------------------
5
93
, 6
- 2
. 3
; 2
C 2
I 6
N 1
T 1
W 2
a 26
b 5
c 8
d 13
e 55
f 11
g 7
h 28
i 32
k 3
l 26
m 17
n 31
o 27
p 12
q 1
r 26
s 22
t 42
u 11
v 8
w 8
y 13
z 1
First off, my program is printing unwanted ascii characters (, ; - etc) and I am working on changing the print function to be more vertical, but I cannot figure out the log method at all. I know log(10) is 1 because 10^1 is 1, but I am having trouble figuring out how to use this to create the method itself. Also, for the extra characters, I tried using:
if(ascii[i] > 65 || ascii[i] < 90 || ascii[i] >= 97 || ascii[i] <= 122 ) {
printf("%c \t %d \n", i, ascii[i]);
}
to no avail. Trying that produced more gibberish characters instead.
Any help/feedback is appreciated.
Soul
The commenters have already pointed out issues with your code. Here's a version that counts only letters and prints vertical labels. It doesn't need <ctype.h> or <math.h>.
Each character hets a letter index which is a number from 0 to 25 for upper and lower case letters and −1 if the character isn't a letter. That reduces the array size to 26.
You could find out each digit with elaborate calculations, but the easiest way is to print the number to a string. snprintf does this for you. You can right-align the number with a field width. The maximum value for a typical int is about 2 billion, which has 10 digits. You should account for that, even if you had to pass in the whole Moby-Dick plus the Bible to get that many counts.
You can test whether you should start printing by assuming a width of ten digits first and checking whether the maximum count has ten digits, that is whether it is 1,000,000,000 or higher. Then divide that limit by 10 in each iteration.
Here's the code:
#include <stdio.h>
// return letter index or -1 for non-letter
int letter(int c)
{
if ('a' <= c && c <= 'z') return c - 'a';
if ('A' <= c && c <= 'Z') return c - 'A';
return -1;
}
int main(int argc, char * argv[])
{
int count[26] = {0}; // letter counts
char label[26][12]; // buffer for printing numbers
int limit = 1000000000; // smallest 10-digit number
int max = 0;
int i, j;
// read and count letters
while (1) {
int c = getchar();
if (c == EOF) break;
c = letter(c);
if (c >= 0) count[c]++;
}
// write auxiliary labels
for (i = 0; i < 26; i++) {
snprintf(label[i], sizeof(label[i]), "%10d", count[i]);
if (count[i] > max) max = count[i];
}
// print vertical labels
for (j = 0; j < 10; j++) {
if (max >= limit) {
for (i = 0; i < 26; i++) {
putchar(' ');
putchar(label[i][j]);
}
putchar('\n');
}
limit /= 10;
}
// print horizontal rule
for (i = 0; i < 26; i++) {
putchar('-');
putchar('-');
}
putchar('-');
putchar('\n');
// print letters
for (i = 0; i < 26; i++) {
putchar(' ');
putchar('A' + i);
}
putchar('\n');
return 0;
}
On your example, it produces:
1
5 1 2 0 2 2 5 8 4 3 6 6 2 5 5 7 2 1 1 2
7 9 8 1 7 2 4 1 0 0 4 5 0 2 2 5 2 6 3 6 6 3 7 0 2 2
-----------------------------------------------------
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
One easy way to figure out how many digits that you'll need is to use sprintf to convert the integer count to a string, and then use strlen to find out how many digits you have. For example:
char str[20] = {0}; // 20 digits should be enough for your case
for (i = 0; i < 128; i++) {
sprintf(str, "%d", ascii[i]);
num_digits = strlen(str);
printf("%d has %d digits\n", ascii[i], num_digits);
}
I didn't test the code, but it should be close.
Some pseudo code
Find max count
Find width of that count when printed w=sprintf(buf, "%d", mxcnt)
Loop w times (wi = 0 to w - 1)
for each non-zero count
form string sprintf(buf, "%*d", w, count[i])
print buf[wi] character
print space
print \n

use of rand function to assign a value randomly [duplicate]

This question already has answers here:
How to create a random permutation of an array?
(3 answers)
Closed 6 years ago.
i am doing a homework. i put rand function in a loop.
int counter = 1;
while ( counter <= 10 ){
variable1 = rand() % 5 + 1;
printf("%d", variable);
counter = counter + 1;
In this code, rand function assigns different value to variable called variable1 but sometimes it assigns same value because range of rand function is narrow. how can i perform that rand function assign different number to variable at the time when loop returns every time.
While rand() is not the greatest random function it should do the trick for many jobs and certainly for most homework. It is perfectly valid to have the same number returned twice in a row from a random function -- as the function should not have any memory of what values were previously returned.
The best way to understand this, is with an example of a coin-toss. Every coin toss is random, and the coin has no memory of the previous toss, so it is possible to flip a coin 32 times in a row and they all comes up head -- if every coin toss is a bit in a 32 bit integer you have created the binary value of integer zero.
However human tend to think (intuition) that having the same value returned more than once is "wrong" for a random function -- but our intuition is wrong on this account.
If you for some reason do want to not repeat the number from one loop to the next, then you will need to program that regardless of which random functions you use -- since any random function would be capable of returning the same values twice.
So something like this would do it;
int counter = 1;
int prevValue = -1;
while ( counter <= 10 ){
do {
variable1 = rand();
} while (variable1 == prevValue);
prevValue = variable1;
variable1 = variable1 % 5 + 1;
printf("%d", variable);
counter = counter + 1;
}
Note that this is still capable of printing the same value twice, since 10 and 15 would be different values before the %5 but would be the same after. If you want the %5 to be taken into account, so the printf never print the same value twice in a row, you would need to move the %5 inside the loop.
In your code snippet i can't find which instruction is the last one inside while. If you want to get different numbers every program run you should use srand() function before while.
But as you mentioned before. Your range (1 - 5) is to narrow to get 10 unique values every time.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int counter = 1;
int variable1 = 0;
srand(time(NULL));
while ( counter <= 10 ) {
variable1 = rand() % 5 + 1;
printf("%d ", variable1);
counter = counter + 1;
}
putchar('\n');
return 0;
}
how can i perform that rand function assign different number to variable at the time when loop returns every time?
I take this to mean OP does not want to generate the same number twice in a row.
On subsequent iterations, use %(n-1)
int main(void) {
int counter;
int variable;
for (counter = 1; counter <= 10; counter++) {
// First time in loop
if (counter <= 1) {
variable = rand() % 5 + 1;
} else {
int previous = variable;
variable = rand() % (5 - 1) + 1;
if (variable >= previous) variable++;
}
printf("%d\n", variable);
}
return 0;
}
In order to generate a unique list of random numbers, you must check each number generated against the list of numbers previously generated to insure there is no duplicate. The easiest way is to store your previously generated numbers in an array to check against. Then you simply iterate over the values in the array, and if your most recent number is already there, create a new one.
For example, you can use a simple flag to check if your are done. e.g.
while (counter < MAXI){
int done = 0;
while (!done) { /* while done remains 0 (not done) */
done = 1;
tmp = rand() % MAXI + 1; /* generate radom number */
for (i = 0; i < counter; i++) /* check again previous */
if (tmp == array[i]) /* if num already exists */
done = 0; /* set as (not done) */
}
array[counter++] = tmp; /* assign random value */
}
Or you can use the old faithful goto to do the same thing:
while (counter < MAXI) {
gennum:
tmp = rand() % MAXI + 1;
for (i = 0; i < counter; i++)
if (tmp == array[i])
goto gennum;
array[counter++] = tmp;
}
Whichever makes more sense to you. Putting together a full example, you could do:
#include <stdio.h>
#include <stdlib.h> /* for rand */
#include <time.h> /* for time */
enum { MAXI = 10 };
int main (void) {
int array[MAXI] = {0}, counter = 0, i, tmp;
srand (time (NULL)); /* initialize the semi-random number generator */
while (counter < MAXI){
int done = 0;
while (!done) { /* while done remains 0 (not done) */
done = 1;
tmp = rand() % MAXI + 1; /* generate radom number */
for (i = 0; i < counter; i++) /* check again previous */
if (tmp == array[i]) /* if num already exists */
done = 0; /* set as (not done) */
}
array[counter++] = tmp; /* assign random value */
}
for (i = 0; i < MAXI; i++)
printf (" array[%2d] = %d\n", i, array[i]);
return 0;
}
(note: the number your mod (%) the generated number by must be equal to or greater than the number of values you intend to collect -- otherwise, you cannot generate a unique list.)
Example Use/Output
$ ./bin/randarray
array[ 0] = 8
array[ 1] = 2
array[ 2] = 7
array[ 3] = 9
array[ 4] = 1
array[ 5] = 4
array[ 6] = 3
array[ 7] = 10
array[ 8] = 6
array[ 9] = 5
A Shuffled Sequence
Given the discussion in the comments, a good point was raised concerning whether your goal was to create unique set of random numbers (above) or a random set from a sequence of numbers (e.g. any sequence, say 1-50 in shuffled order). In the event you are looking for the latter, then an efficient method to create the shuffled-sequence is using a modified Fisher-Yates shuffle knows as The "inside-out" algorithm.
The algorithm allows populating an uninitialized array with a shuffled sequence from any source of numbers (whether the source can be any manner of generating numbers). Essentially, the function will swap the values within an array at the current index with the value held at a randomly generated index. An implementation would look like:
/** fill an uninitialized array using inside-out fill */
void insideout_fill (int *a, int n)
{
int i, val;
for (i = 0; i < n; i++) {
val = i ? randhq (i) : 0;
if (val != i)
a[i] = a[val];
a[val] = i; /* i here can be any source, function, etc.. */
}
}
(where randhq is any function that generates a random value (0 <= val < n))
A short example program that uses the function above to generate a shuffled array of value from 0 - (n-1) is shown below. The example generates a shuffled sequence of values in array using the inside-out algorithm, and then confirms the sequence generation by sorting the array:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void insideout_fill (int *a, int n);
int randhq (int max);
void prnarray (int *a, size_t n, size_t strd, int wdth);
int intcmp (const void *a, const void *b);
int main (int argc, char **argv) {
srand (time (NULL));
int arrsz = argc > 1 ? (int)strtol (argv[1], NULL, 10) : 50;
int array[arrsz];
insideout_fill (array, arrsz);
printf ("\n array initialized with inside-out fill:\n\n");
prnarray (array, arrsz, 10, 4);
qsort (array, arrsz, sizeof *array, intcmp);
printf ("\n value confirmation for inside-out fill:\n\n");
prnarray (array, arrsz, 10, 4);
return 0;
}
/** fill an uninitialized array using inside-out fill */
void insideout_fill (int *a, int n)
{
int i, val;
for (i = 0; i < n; i++) {
val = i ? randhq (i) : 0;
if (val != i)
a[i] = a[val];
a[val] = i; /* i here can be any source, function, etc.. */
}
}
/** high-quality random value in (0 <= val <= max) */
int randhq (int max)
{
unsigned int
/* max <= RAND_MAX < UINT_MAX, so this is okay. */
num_bins = (unsigned int) max + 1,
num_rand = (unsigned int) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
int x;
/* carefully written not to overflow */
while (num_rand - defect <= (unsigned int)(x = rand()));
/* truncated division is intentional */
return x/bin_size;
}
/** print array of size 'n' with stride 'strd' and field-width 'wdth' */
void prnarray (int *a, size_t n, size_t strd, int wdth)
{
if (!a) return;
register size_t i;
for (i = 0; i < n; i++) {
printf (" %*d", wdth, a[i]);
if (!((i + 1) % strd)) putchar ('\n');
}
}
/** qsort integer compare */
int intcmp (const void *a, const void *b)
{
return *((int *)a) - *((int *)b);
}
Example Use/Output
$ ./bin/array_io_fill
array initialized with inside-out fill:
40 15 35 17 27 28 20 14 32 39
31 25 29 45 4 16 13 9 49 7
11 23 8 33 48 37 41 34 19 38
24 26 47 44 5 0 6 21 43 10
2 1 18 22 46 30 12 42 3 36
value confirmation for inside-out fill:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
Look it over and let me know if you have any questions.

Pass string to main and break up into array

I am passing arguments to main with this code:
#include <stdio.h>
int main(int argc, char ** argv)
{
int i = 1;
for(i = 1; i < argc; i++)
printf("%c", argv[i]);
return 0;
}
So I use ./test 218 abc 392990xFF[w2 dlx which works fine. However, the array is:
arr[1] = "218"
arr[2] = "abc"
arr[3] = "392990xFF[w2"
arr[4] = "dlx"
I want the array to be like this:
arr[0] = '2'
arr[1] = '1'
arr[2] = '8'
arr[3] = 'a'
etc...
How can I achieve this without putting a space after each digit or character?
The arguments passed by the run time environment to the program can be captured by main using int argc, char** argv only. If you have a need to combine them into one large array, you'll need to write the code for that, or print them one character at a time.
int main(int argc, char ** argv)
{
int i = 1;
int j;
int len;
for(i = 1; i < argc; i++)
{
len = strlen(argv[i]);
for ( j = 0; j < len; ++j )
{
printf("%c", argv[i][j]);
}
}
return 0;
}
First of all this is not what it will print -
arr[0] = "218"
arr[1] = "abc"
arr[2] = "392990xFF[w2"
arr[3] = "dlx"
argv[0] will store ./test. And "218" will be on index 1 thus others similarly .
And also printf("%c", argv[i]); .%c expects a char and you pass a string which is incorrect.
Solution could be -
#include <stdio.h>
int main(int argc, char ** argv)
{
int i = 1,j;
for(i = 1; i <argc; i++)
for(j=0;argv[i][j]!='\0';j++)
printf("%c\n", argv[i][j]);
return 0;
}
Rather than a for loop, you can also simply use pointers and while loops instead. There are generally many ways to solve problems in C:
#include <stdio.h>
int main (int argc, char **argv) {
int i = 1;
int j = 0;
while (i < argc) {
char *p = argv[i];
while (*p) {
printf (" arr[%2d] = \"%c\"\n", j++, *p);
p++;
}
i++;
}
return 0;
}
Output
$ ./bin/argvchars 218 abc 392990xFF[w2 dlx
arr[ 0] = "2"
arr[ 1] = "1"
arr[ 2] = "8"
arr[ 3] = "a"
arr[ 4] = "b"
arr[ 5] = "c"
arr[ 6] = "3"
arr[ 7] = "9"
arr[ 8] = "2"
arr[ 9] = "9"
arr[10] = "9"
arr[11] = "0"
arr[12] = "x"
arr[13] = "F"
arr[14] = "F"
arr[15] = "["
arr[16] = "w"
arr[17] = "2"
arr[18] = "d"
arr[19] = "l"
arr[20] = "x"
Determine the total number of characters in all of the strings, then allocate a new character array of that length, and then copy the input characters into the new array.
The last part could take advantage of the sizes you gather in the first part: have an outer loop over all the argument strings, with an inner loop over the characters in each string.
EDIT: Now that I'm not on a mobile device, here's the above in code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char ** argv)
{
//For storing sizes of each input string
int *arg_chars;
//Where the individual characters are stored
char *stored_chars;
/* Determine total number of characters, and store
characters in each word for later re-use */
arg_chars = malloc(argc * sizeof(int));
int total_chars = 0;
//Loop starts at 1 since we don't care about arg 0
for(int i=1; i<argc; i+=1)
{
arg_chars[i] = strlen(argv[i]);
total_chars += arg_chars[i];
printf("Word %d is %d long\n", i, arg_chars[i]);
}
/* Load argument characters into the stored_chars array */
stored_chars = malloc(total_chars * sizeof(char));
int current_char = 0;
//Loop starts at 1 to exclude the program name (arg 0)
for(int i = 1; i < argc; i+=1)
{
printf("Scanning word %d (%s):\n", i, argv[i]);
for(int j = 0; j < arg_chars[i]; j+=1)
{
stored_chars[current_char] = argv[i][j];
printf(" Stored letter %d `%c` (letter %d of word %d)\n", current_char, argv[i][j], j, i);
current_char += 1;
}
}
/* Demonstrate that it's all loaded and accessible in any order */
for(int i=total_chars-1; i >= 0; i-=1)
{
printf("stored_chars[%d] = `%c`\n", i, stored_chars[i]);
}
return 0;
}
Output:
Word 1 is 3 long
Word 2 is 3 long
Word 3 is 12 long
Word 4 is 3 long
Scanning word 1 (218):
Stored letter 0 `2` (letter 0 of word 1)
Stored letter 1 `1` (letter 1 of word 1)
Stored letter 2 `8` (letter 2 of word 1)
Scanning word 2 (abc):
Stored letter 3 `a` (letter 0 of word 2)
Stored letter 4 `b` (letter 1 of word 2)
Stored letter 5 `c` (letter 2 of word 2)
Scanning word 3 (392990xFF[w2):
Stored letter 6 `3` (letter 0 of word 3)
Stored letter 7 `9` (letter 1 of word 3)
Stored letter 8 `2` (letter 2 of word 3)
Stored letter 9 `9` (letter 3 of word 3)
Stored letter 10 `9` (letter 4 of word 3)
Stored letter 11 `0` (letter 5 of word 3)
Stored letter 12 `x` (letter 6 of word 3)
Stored letter 13 `F` (letter 7 of word 3)
Stored letter 14 `F` (letter 8 of word 3)
Stored letter 15 `[` (letter 9 of word 3)
Stored letter 16 `w` (letter 10 of word 3)
Stored letter 17 `2` (letter 11 of word 3)
Scanning word 4 (d1x):
Stored letter 18 `d` (letter 0 of word 4)
Stored letter 19 `1` (letter 1 of word 4)
Stored letter 20 `x` (letter 2 of word 4)
stored_chars[20] = `x`
stored_chars[19] = `1`
stored_chars[18] = `d`
stored_chars[17] = `2`
stored_chars[16] = `w`
stored_chars[15] = `[`
stored_chars[14] = `F`
stored_chars[13] = `F`
stored_chars[12] = `x`
stored_chars[11] = `0`
stored_chars[10] = `9`
stored_chars[9] = `9`
stored_chars[8] = `2`
stored_chars[7] = `9`
stored_chars[6] = `3`
stored_chars[5] = `c`
stored_chars[4] = `b`
stored_chars[3] = `a`
stored_chars[2] = `8`
stored_chars[1] = `1`
stored_chars[0] = `2`

Resources