I can't print char array's elements with for loop - c

#include <stdio.h>
int main() {
char usernames[5][10] = {"Lebron","Davis","Schroder","KCP","Gasol"};
int i = 0;
for(i=0; i < 20; i++) {
printf("%s\n",usernames[i][20]);
}}
Hello guys, I'm new at programming and I study for use for loop with char arrays. You can see my code in top. The output I want to print is;
Lebron
Davis
Schroder
KCP
Gasol
I put my i into char's second dimension, is it not true? Basically, I want to print all the elements in my array, how can I do it? Thanks in advance.

Here you are storing data into 2d array. So, each row will store a sequence of char or a string . like usernames[0] = "Lebron" and so on. So, array length will be 5 . But you are trying to print 20 elements. that will give you runtime error.
here is the solution that will work for you.
#include <stdio.h>
int main() {
char usernames[5][10] = {"Lebron","Davis","Schroder","KCP","Gasol"};
int i = 0;
for(i=0; i < 5; i++) {
printf("%s\n",usernames[i]);
}
return 0;
}

Related

get a number of elements in 2d array, in shape of (*array)[column]

I declared a 2d array in main function and I want to get the number of elements in another function.
Let's say my main is like this.
#define col 100
#define row 10
int main(){
array[row][col] = {"abc1", "abc2", "abc3"};
int len = get2DLen(array);
}
and I copied this array in this form (*array)[column]
int get2DLen(char (*array)[col]){
int len;
//some operations..
return len;
}
Questions are..
how can I get col in func? In this case, 10.
how can I get the number of actual elements in the array? In this case, 3.
I'm aware of the fact that array means *array[0] in here.
I tried to iterate all the elements and check if it's '\0' like a normal char array string. But it's just absolutely wrong.. cause it was initialized anyway..
so any help would be appreciated
In C, it's not possible to determine the size of the array. Therefore, you can't get col in the function. You need to pass the dimension of the array to the function parameter.
#include <stdio.h>
#include <stddef.h>
#define col 100
#define row 10
int get2DLen(char (*array)[], size_t arr_row, size_t arr_col)
{
int len = arr_col;
return len;
}
int main()
{
char array[row][col] = {"abc1", "abc2", "abc3"};
int len = get2DLen(array, 3, 4);
printf("%d", len);
}

Initialize the arrays inside an array of char* using a loop

I need to create an array of strings, each representing a card of the Spanish deck:
#define __USE_MINGW_ANSI_STDIO 1
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char *type[4]= {"copas", "basto", "espada", "oro"};
char *number[10]= {"Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "Diez", "Once", "Doce"};
char *deck[40];
int deckIndex= 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 10; j++) {
char card[100] = "";
strcat(card, number[j]);
strcat(card, " de ");
strcat(card, type[i]);
strcat(card, "\n");
deck[deckIndex]= card;
deckIndex++;
}
}
for (int i = 0; i < 40; i++)
{
printf("%s\n", deck[i]);
}
return 0;
}
However, all entries of deck[] point to the same string. As a result, "Doce de oro" is printed 40 times. I don't understand why this happens, but I've theorized it's because card[] is being reinitialized in the same memory direction, and overrides what was already written there in the previous iteration. If I'm right, I would have to declare every array separately, but I have no idea how to do that without writing 40 different arrays.
Tldr:
¿Why do all entries of deck[] point to the same location?
¿How do I fix it?
(Btw suggestions for a better title are appreciated)
In C, memory on the stack is allocated in terms of Scopes. So yes, your theory is right. You are rewriting on the same location.
To fix your program, there are two possible solutions I can think of.
You can use Multidimensional Arrays.
Or you can allocate memory in heap using malloc (but make sure to free it once you are done with it)
As pointed out in the comments, in the deck[deckIndex]= card; line, you are assigning the same pointer1 to each of your deck elements – and, worse, a pointer to a variable (the card array) that is no longer valid when the initial nested for loop goes out of scope.
To fix this, you can make copies of the card string, using the strdup function, and assign the addresses of those copies to the deck elements. Further, as also mentioned in the comments, you can simplify the construction of the card string using a single call to sprintf, rather than using multiple strcat calls.
Here's how you might do that:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char* type[4] = { "copas", "basto", "espada", "oro" };
char* number[10] = { "Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "Diez", "Once", "Doce" };
char* deck[40];
int deckIndex = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 10; j++) {
char card[100] = "";
sprintf(card, "%s de %s", number[j], type[i]);
deck[deckIndex] = strdup(card);
deckIndex++;
}
}
for (int i = 0; i < 40; i++) {
printf("%s\n", deck[i]);
}
// When you're done, be sure to free the allocated memory:
for (int i = 0; i < 40; i++) {
free(deck[i]);
}
return 0;
}
If your compiler does not support the strdup function (most do, and it is part of the ISO C Standard from C23), writing your own is very simple:
char* strdup(const char *src)
{
char* result = malloc(strlen(src) + 1); // Add one to make room for the nul terminator
if (result) strcpy(result, src);
return result;
}
1 Well, formally, a new card array is born on each iteration of the inner for loop, but it would be a very inefficient compiler that chose to do that, rather than simply re-using the same memory – which is clearly what is happening in your case.

Develop a table of strings in a two-dimensional table

I have this exercise that i can't understand and i hoped somebody could help me with it.
Develop a function that receives a table of strings, each one
with a maximum of 40 characters, and return the index of the largest of them. Note: The function receives a two-dimensional table, with the first dimension of the table not specified.
My question is how do i use the two dimensional table in this exercise i normally only used the a normal array to do strings, and after that what is exactly the index of a string? Is its lenght? Because if it is i know how to do the problem using the function strlen. I just dont understand how the table will work. If somebody can please help me (sorry for my bad english).
code
This means, your function should work like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int func (char table[][40], int numentries) {
...
}
int main (void) {
int index;
char example[][40] = {
"this",
"is",
"an",
"example",
"with",
"seven",
"words"
};
index = func(example, 7);
printf("The longest word has index %d\n", index);
exit(EXIT_SUCCESS);
}
(maybe it should even be 41 instead of 40 to have space for the zero-byte, depending if this is already counted in or not in the specification)
Now, each entry of the table has at most 40 characters, but the number of entries is unspecified and has to be passed in a separate argument.
You can iterate over the table from i = 0 up to numentries and find the element with the greatest length. The corresponding i is the index you have to return.
Here is an example, make sure you understand what was done- if something is unclear- ask. I hope this helps:
Note that if there are multiple max the index returned will be for the first string of that length.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int GetLongestString(char sArr[][40], int row)
{
int i = 0;
int max = 0;
int maxindex = -1;
for(i= 0 ; i< row; ++i) /*to check each row*/
{
if(max < strlen(&sArr[i][0])) /*gives the add of each rows string beginning for
the strlen function */
{
max = strlen(&sArr[i][0]);/*get the max value and store it for later
checks*/
maxindex = i;/* save the index of max length*/
}
}
return maxindex;
}
int main()
{
int res = 0;
char array[2][40] ={"all", "hello"};
char array2[2][40] ={"hello", "all"};
res = GetLongestString(array,2);
printf("%d\n", res);
res = GetLongestString(array2,2);
printf("%d\n", res);
return 0;
}
Good luck!

C: ERROR After mallocing and passing 2D char array to function

I don't understand what is wrong with the code below. It should malloc a 2D char array[5][30] (referred as LENGTH), pass it to a function and fill it with a string. It works just fine in the function; I can print it from there without any problem. But i cannot print even the first one from within the main() function (the application crashes if I try).
Could somebody please explain what I am doing wrong?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH 5
void fillArray(char array[][LENGTH]) {
for (int i = 0; i < 5; i++) {
strcpy(array[i],"Hi World");
}
for (int i = 0; i < 5; i++) {
printf("%s\n",array[i]);
}
}
int main() {
char** array = (char**)malloc(5*sizeof(char*));
for (int i = 0; i < 5; i++) {
array[i] = (char*)malloc(LENGTH);
}
fillArray(array);
printf("%s",array[0]);
getchar();
return 0;
}
From main() function you are passing double pointer array and catching with 2D array array[][LENGTH] which is not correct, just saying double pointer is not similar to 2D array & vice versa.
for your task in fillArray() use array of char pointer as a argument, how many ? LENGTH.
void fillArray(char *array[LENGTH]) { /* this is okay */
for (int i = 0; i < 5; i++) {
strcpy(array[i],"Hi World");/*now in `array[i]` you can store any no of char. */
}
for (int i = 0; i < 5; i++) {
printf("%s\n",array[i]);
}
}
Also casting malloc() is not required And once job is done at last don't forget to free the dynamically allocated memory by calling free() for each.
The basic problem is that your function expects a 2 dimensional array but that is not what you pass to the function.
In main you allocate a 1 dimensional array of pointers. Then for each of these pointers, you allocate a 1 dimensional array of chars. That is not a 2D array.
So your function doesn't get what it expects and therefore your program fails.
So instead of:
char** array = (char**)malloc(5*sizeof(char*));
for (int i = 0; i < 5; i++) {
array[i] = (char*)malloc(LENGTH);
}
try this:
char (*array)[LENGTH] = malloc(5*LENGTH*sizeof(char*));
to get a correctly malloc'ed 2D array.
BTW:
I think you have a bug here
#define LENGTH 5
^
I guess you want 30 instead of 5

Garbage characters in string

I've written code to make a right pyramid out a character.
However, when I execute the program, the last two lines of the pyramid have garbage characters placed after them even when it exceeds the size of the array.
The code is here:
#include <stdio.h>
#include <string.h>
#define ROW 5
int main(void) {
char array[ROW];
int x = 0;
int row = 0;
for (row = 0; row < ROW; row++) {
array[x] = 'a';
if (x < ROW) {
printf("%s\n", dolla);
}
x++;
}
getchar();
}
Where are the garbage characters coming from? It's only on lines after the third.
The problem in your code is that you have not terminated your string with \0 (null) character. Here's a workout for your code:
#include <stdio.h>
#include <string.h>
#define ROW 5
int main(void)
{
char array[ROW];
int x = 0;
int row = 0;
for(row = 0; row < ROW; row++)
{
array[x] = 'a';
if(x < ROW)
{
array[x+1]='\0';
printf("%s\n", array);
}
x++;
}
getchar();
}
I'm no specialist, but I've read the following in many typical C books:
int arrays in C are initialized to 0, while char arrays are initialized to garbage.
And yeah, forgot to mention, it's no dolla, it's array.
char array[ROW+1] = {0}; will help you a lot. You might have assumed array was empty but it was full of random characters. By initializing with {0}, the array starts with all zeroes.
I'm going to assume dolla was a transcription error and that either dolla should be array or that array used to be named dolla.
You are probably exceeding the values in the array to make the pyramid which results in printing out garbage values that were there before you even compiled your code.
When you print the values, rather than printing out whole array ( which means there can be garbage values included ) you can print up to the point where you have valid values and this can be done by introducing a null character '\0' at the end of the array.
Also initializing you array would be a better choice here as then you can debug your code better after seeing the output.

Resources