Garbage characters in string - c

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.

Related

Count occurrences of a string character in an array

int count(char letter, int* array, int number)
{
int sum= 0;
int i;
for(i = 0; i < number; ++i)
{
if(array[i] == letter)
++sum;
}
return sum;
}
int main(){
char array[] = { 'A','B','B','C'};
int number= sizeof(array) / sizeof(char);
count("A", array, number);
return 0;
}
I am attempting to count an occurrence of a particular character in an array and get nothing. The problem is certainly in the way I pass the character argument, but I struggle to find a similar example online.
I did a bit of tweaking of your code so that the parameters in your function align with the parameters passed when your function is called. Following is an example of what your code might look like in order to count characters.
#include <stdio.h>
#include <stdlib.h>
int count(char letter, char* array, int number) /* Made second parameter a character array in lieu of an integer array */
{
int sum= 0;
int i;
for(i = 0; i < number; ++i)
{
if(array[i] == letter)
++sum;
}
return sum;
}
int main()
{
char array[] = { 'A','B','B','C'};
int number= sizeof(array) / sizeof(char) ;
printf("Count: %d\n",count('A', array, number)); /* Changed from string constant "A" to character 'A' */
return 0;
}
First off, you appear to want to send a character as your first parameter to your function. In your original code you were actually sending a string constant as "A" was enclosed in double quotes and not single quotes. The second parameter is a character array (aka, a string). Therefore, in your function definition the second parameter there needs to be a character array and not an integer array. Characters take up one or two bytes of memory depending upon the system, and integers "usually" take up four bytes of memory. So there would be a mismatch in attempting to check out array values.
Using your revised function to produce output for a "printf" call, I received the following output on my terminal.
Count: 1
So probably the biggest takeaway from this is that characters (e.g. 'A') are different from string constants (e.g. "A"), and characters, even though they equate to an integer value, utilize a smaller chunk of memory than do integers.
Hope that helps.
Regards.

Returns a new string with characters from two other strings

Write a function common_char that takes two strings as arguments and returns a new string that contains a single copy of all characters that appear in either of the two strings.
For example, string1: hello; string2: world; the new string is : hellowrd (o and l were already in array from hello).
May use string function here.In other words, all characters in string1 are copied into the new string, but characters in string 2 are copied only characters that are not in string1. That is past exam question and the university did not provide answer. Here is my code.
#include <stdio.h>
#include <string.h>
char *common_char(char *string1, char *string2) {
int str_length1 = strlen(string1);
int str_length2 = strlen(string2);
char *new_string = malloc(str_length1+str_length2+1);
for (int index_1 = 0; index_1 < str_length1; index_1++) {
for (int index_2 = 0; index_2 < str_length2; index_2++) {
if (string1[index_1] == string2[index_2]) {
}
}
}
}
int main(void) {
return 0;
}
My idea is to find duplicate characters in string 2 and string 1 according to the nested loop, but there is a problem with the conditional statement, there is red line, also how to copy the character of the non-duplicate string? I know strcopy(), but how to remove the repeated characters?
I've come up with a solution that uses dynamic memory and resizes the result char* each time a new char must be added. There are two loops, the first iterates the b string and the second loop checks that non of char of the b string is repeated in the a string, if it is not repeated, then adds it. Hope you understand the realloc to resize dynamically the char* each time it must be added an element.
Firstly I initialize the result string to the size of string a so it can be all copied inside. The ordering method I think it is called bubble method.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* common_char(char* a, char* b) {
char* result = (char*)malloc(sizeof(char)*strlen(a)+1);
int i = 0;
int j = 0;
int repeated = 0;
strcpy(result,a);
for(i=0; i<strlen(b); i++) {
for(j=0; j<strlen(result); j++) {
if(b[i] == a[j]) {
repeated = 1;
}
}
if(!repeated) {
result = (char*)realloc(result,strlen(result)+sizeof(char));
result[strlen(result)] = b[i];
result[strlen(result)+1] = '\0';
}
repeated = 0;
}
return result;
}
int main()
{
char a[] = "hello";
char b[] = "world";
char* result = common_char(a,b);
printf("%s", result);
return 0;
}
EDIT: I've modified the code to make it function. About the comment of memory allocation, I've modified the declaration of result to give it space for the '\0'. When doing the realloc, I've already considered that the realloc does not increment the strlen() because strlen() is a counter till the '\0' not of the size of the variable.

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

#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;
}

integers displayed instead of a sorted string

i want to sort a string using counting sort but instead of a sorted string some integer values are displayed with a warning iteration 254u invokes undefined behavior pointing at the expression c[i]+=c[i-1] even though the iterations doesn't seem to exceed the signed int limit
the code is
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define range 255
void count_sort(char arr[],int n)
{
int c[range];
int i;
memset(c,0,sizeof(c));
char b[strlen(arr)];
for(i=0;i<n;i++)
{
++c[arr[i]];
}
for(i=1;i<=range;++i)
{
c[i]+=c[i-1];
}
for(i=n-1;i>=0;--i)
{
b[c[arr[i]]-1]=arr[i];
--c[arr[i]];
}
for(i=0;i<n;i++)
{
arr[i]=b[i];
}
}
void print(char arr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d ",arr[i]);
}
}
int main()
{
char arr[]="november";
int n=sizeof(arr)/sizeof(arr[0]);
count_sort(arr,n);
print(arr,n);
return 0;
}
what changes are required to make the code run correctly
I checked you here link. The code is correct except for the lines below
(1) printf("%d ",arr[i]);
Change this line to the following since you are printing characters and not integers.
printf("%c ",arr[i]);
If you keep %d then you are casting the char to an integer, and you'll get the ascii value. So for %d specifier, you will get a sorted array of integer values which are ascii values for the corresponding characters.
(2) int c[range];
Change the line to the following
int c[range+1];
Now in your second for loop, it will not exceed the bounds of the array c and you will not get the undefined behavior.
Hope this will help you.
Here are some points that I'd like to share:
You're using %d as format specifier in printf() in print function so change that to %c like this:
printf("%c ", arr[i]);
If your string is properly \0 terminated and you can do without printing space between characters then you can directly use printf() with %s it:
printf("%s", arr);
You don't need the custom print() function in this case.
This loop
for ( int i = 1; i <= range; ++i ) // <== out-of-bounds
{
c[i] += c[i-1];
}
is causing out-of-bounds access resulting in Undefined Behavior. As range represents 255 but the loop condition is i <= range whereas it should be i < range to keep the iterations in the valid range i.e. 0-254.
You are calculating the length of the string like this:
int n = sizeof(arr) / sizeof(arr[0]);
sizeof also calculates the terminating '\0' character so the length of the string will be:
sizeof( arr ) = 9
sizeof( arr[0] ) = 1
n = 9 / 1 = 9
But, the length of the string november is 8. strlen() would be a better choice here.
int n = strlen( arr );
Or,
int n = sizeof( arr ) - 1; // don't include `\0`
In the count_sort function, you're declaring the arrayc like this:
int c[range];
And, then using memset to set it. You could initialize it like this:
int c[range] = {0};
More on memset here.
The array b is declared like this:
char b[strlen(arr)];
^^^^^^^^^^^
But, you already have n, use that. You don't need to calculate the length again.
You should use %c instead of %d to print the characters.
You should also use for( i=1; i < range; i++ ), i <= range will give fault as last index of array is range-1.
there are some problem in you code first you are using wrong format specifier for printing chars.You have to use %c instead of %d in your printing function.
also you should remove = from this loop for(i=1;i<=range;++i) , otherwise you will pass boundaries of array c which will lead to undefined behavior , or if you need that element you should declare c[range+1] instead of c[range].
also note that in your sorting since ASCII code of \0 is smallest , it will become first element of your array and so neither b nor arr will be terminated.
I suggest this loop:
for (i = n - 2; i >= 0; --i)
{
b[c[arr[i]] - 2] = arr[i];
--c[arr[i]];
}
b[n-1] = '\0';

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!

Resources