Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
This code is an exercise from a daily programming mailing list. I am trying to print out a list of given words in reverse order. The words are delimited by spaces. When running the code below, it enters into an infinite loop just printing the (new) first word. I have looked through the conditions and everything looks OK to me. I think it may take a fresh set of eyes to point out a simple mistake, but I can't find anything. Thanks to anyone who can lend a hand.
*Note: I am planning on adding back in the spaces to the output after this is figured out. I am aware the output will just be one long string without spaces so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char *words;
words = "here world hello spam foo bar baz";
int space_indices[10];
int counter = 0;
// Find the spaces and keep track of the index numbers in the space_indices array
for (int i = 0; i < strlen(words); i++) {
if (words[i] == ' ') {
space_indices[counter] = i;
counter++;
}
}
for (int i = counter - 1; i >= 0; i--) {
if ( i = counter - 1) {
// Print the first word
for (int j = space_indices[i] + 1; j < strlen(words); j++) {
printf("%c", words[j]);
}
} else if (i >= 0) {
// Print the other words except for the last
for (int j = space_indices[i] + 1; j < space_indices[i + 1]; j++) {
printf("%c", words[j]);
}
} else {
// Print the last word
for (int j = 0; j < space_indices[0]; j++) {
printf("%c", words[j]);
}
}
}
}
As Havenard explained, the problem was that I was not using a comparison operation, I was using an assignment operator.
This:
if ( i = counter - 1)
should be:
if ( i == counter - 1)
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Story: I tried to convert a c99 script to regular gcc.
Problem: The output is empty.
Expected output: 3,2,1
length is the number of elements in the array.
Update: the script is designed to sort the elements of the array in a descending order.
The code:
#include <stdio.h>
int main() {
int arr[] = { 1,2,3 };
int temp = 0;
int length = sizeof(arr) / sizeof(arr[0]);
int i = 0;
int j = i + 1;
for (i < length; i++;) {
for (j < length; j++;) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
int y = 0;
for (y < length; y++;) {
printf("%d ", arr[y]);
}
return 0;
}
Your syntax for for loops is the issue.
Here is the correct way to write your loops.
int i, j;
for (i = 0; i < length; ++i) // for (initialisation; test condition; operation)
{
for (j = i + 1; j < length; ++j) // note that j is initialized with i + 1 on each iteration of
// the outer loop. That's what makes the bubble sort work.
{
/* test and swap if needed */
}
}
for (i = 0; i < length; ++i) // note that i is reset to zero, so we can scan the array from
// a known position (the top) to bottom.
{
/* printout */
}
Your semicolon is in the wrong place, move it to the far left just inside the parentheses.
Loop syntax is:
for (intializer; break condition; iterator)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This code need to save friends in some array of array(pointer to pointer) and by the length of the names do realloc (build exactly dynamic place for the strings of each of them) and than prints the string and the length and free everything.
So the code work when i debugging but when I running it with CTR+f5 it's crashed after the fgets of the first string. also all the free loops and the free function doesn't work me here, but if remove it the debugging still work and the CTR+f5 still don't work. help someone?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LENGTH 20
int main(void)
{
int i = 0, j = 0,friends=0;
char str[LENGTH];
printf("Hello bro,how U doin'?\nTell me how many friends do you have?\n");
scanf("%d",&friends);
char** friendBook = (char**)malloc(sizeof(char)*friends);
if (friendBook)
{
getchar();
for (i = 0; i < friends; i++)
{
*(friendBook+ i) = malloc(LENGTH*sizeof(char));
}
for (i = 0; i < friends; i++)
{
printf("Enter friend number: %d\n", i + 1);
fgets(str, LENGTH, stdin);
str[strcspn(str, "\n")] = 0;
*(friendBook + i) = (char*)realloc(*(friendBook+i),(sizeof(char)*strlen(str))); // dynamic memory for every string(name)
if (*(friendBook + i))
{
strcpy(*(friendBook+i),str);
}
}
for (i = 0; i < friends; i++)
{
printf("Friend: %s\tLength of friend name %d\n", *(friendBook + i), strlen(*(friendBook + i)));
}
}
for (i = 0; i <friends; i++)
{
free(*(friendBook+i));
}
free(friendBook);
system("PAUSE");
return 0;
}
Take the string "Hello". strlen ("Hello") = 5. But to store it, you need SIX bytes, not five, because there is a zero byte at the end that doesn't get counted by strlen.
PS. Undefined behaviour when you try to print strlen with %d format. Can crash, print nonsense, or worse. Use %zd. Turn all warnings on in your compiler and fix them.
PS. BLUEPIXY spotted a much worse problem...
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am really struggling with learning programming via C. I seem to get the gist of things while going through the book's exercises but the second I try to implement something different it falls apart especially in regard to arrays.
I am making a simple game with a 2D character array. It should be 11x11. I am trying to write a function to set each index of the array as a blank space ' ' to start. My code compiles then I get a 'core dump' when I run it. Here is the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*-------- GLOBAL FUNCTIONS --------*/
// Clear the Screen
void clear()
{
system("clear"); // For Linux/iOS
}
//---------- Creat Array(Game Board)
#define MAX 11 // Max number of characters in each row and column of array
char GameBoard[MAX][MAX];
// Clear Each Space in Array with Empty ("") Space
void ClearBoard(char GB[MAX][MAX])
{
for (int i = 0; i < MAX; ++i)
{
GameBoard[i][i] = ' ';
for (int j = 0; j < MAX; ++i)
{
GameBoard[i][j] = ' ';
}
}
}
int main()
{
ClearBoard(GameBoard);
return 0;
}
Any help towards understanding this better would be greatly appreciated, thank you.
your inner loop increments i until it is out of the array bounds
it should be ++j and not ++i
after MAX+1 iterations of the inner loop you're trying to access memory which is not allocated and that is why you get your error.
also the line GameBoard[i][i] = ' '; is unnecessary since it is taken care of in the inner loop when j == i
You need to change this line
for (int j = 0; j < MAX; ++i)
to
for (int j = 0; j < MAX; ++j)
Replace ++i with ++j in the line
for (int j = 0; j < MAX; ++i)
GameBoard[i][i] = ' ';
This line doesn't make any sense. Remove it.
for (int j = 0; j < MAX; ++i)
Should be j++.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
Well, my question is pretty simple, yet i've been stuck for quite a while. I'd like to write a program that takes two arrays as arguments, and then write the letters in it without duplicates, in order of appearance.
example :
$ ./a.out bulwark blue
bulwarke
$ ./a.out fresh feeling
freshling
$ ./a.out final01 test02
final01tes2
I tried a few ways, but can't figure how to do it without malloc. The tricky thing is, I cannot use malloc, the only authorized function is "write"
P.S : Sorry for my bad English
Use an auxiliary array to indicate which letter has already been used:
void func(char arr1[],char arr2[])
{
int hash[256] = {0};
for (int i=0; arr1[i]!=0; i++)
{
unsigned char letter = (unsigned char)arr1[i];
if (hash[letter] == 0)
{
hash[letter] = 1;
printf("%c",letter);
}
}
for (int i=0; arr2[i]!=0; i++)
{
unsigned char letter = (unsigned char)arr2[i];
if (hash[letter] == 0)
{
hash[letter] = 1;
printf("%c",letter);
}
}
printf("\n");
}
Note: this code assumes that each of the input strings (arr1 and arr2) is terminated with a 0 character.
Just keep track what you have printed. The follow will work just fine for char, because there are so few of them. Keeping track of unicode chars with an array that is long enough for all possible values would be mad. In such case inserting identifiers to a hash would probably be better option, but since unicode was not part of the consideration the following should be good enough.
#include <stdio.h>
int main(int argc, char **argv)
{
char arr[256] = { 0 };
int i, j;
for (i = 1; i < argc; i++)
for (j = 0; argv[i][j]; j++)
if (!arr[argv[i][j]]) {
arr[argv[i][j]] = 1;
printf("%c", argv[i][j]);
}
putchar('\n');
return 0;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Assume the character a,b,c,d,e represent the number 1 to 9, and they cannot be equal to
each other.
Question:
How many equals that can meet (ab * cde = adb * ce).
Example:
36 * 495 = 396 * 45.
Here is my code,and the result is right.However,i think my code is too awkward,especially in (if(a!=b&&a!=c&&a!=d&&a!=e&&b!=c&&b!=d&&b!=e&&c!=d&&c!=e&&d!=e&&c*d*e!=0))
I would appreciate it if someone could give me a better solution.
#include<stdio.h>
main(){
int a,b,c,d,e,m,n,i=0;
long f1,f2,f3,f4;
for(m=11;m<=99;m++){
a=m/10;
b=m%10;
if(a!=b&&a*b!=0)
{
for(n=101;n<=999;n++)
{
c=n/100;
d=n%100/10;
e=n%10;
if(a!=b&&a!=c&&a!=d&&a!=e&&b!=c&&b!=d&&b!=e&&c!=d&&c!=e&&d!=e&&c*d*e!=0)
{
f1=a*10+b;
f2=c*100+d*10+e;
f3=a*100+d*10+b;
f4=c*10+e;
if(f1*f2==f3*f4) i++;
printf("\n%d%d*%d%d%d*=%d%d%d*%d%d\n",a,b,c,d,e,a,d,b,c,e);
}
}
}
}
printf("%d\n",i);
return 0;
}
If you can, instead of
int a,b,c,d,e;
Try to use
int numbers[5];
And then to check if your numbers are all different, you can use for loops
doubleOccurence = FALSE; /* where FALSE = 0 */
for (i=0; i < 4; i++) {
for (j=i+1; j < 5; j++) {
doubleOccurence = doubleOccurence || (numbers[i] == numbers[j]);
}
}
It looks a bit clearer to me.
Unfortunately you can't really iterate through a list of variables you are better off with an array of numbers like Julien mentions in his answer.
int nums[5];
replace a with nums[0], b with nums[1], etc....
But then I would go one step further to tidying up your code and call a function that takes in the array to check uniqueness:
if(listIsUnique(nums, 5)) // yes hardcoded the 5, but that can be sorted
{
...
}
And then:
bool listIsUnique(int* nums, int len)
{
for (int i = 0; i < len; i++)
for (int j = i + 1; j < len; j++)
if (nums[i] == nums[j])
return false; // return false as soon as you find a match - slightly faster :)
return true; // if we get here its a unique list :)
}
Note: code is untested, there may be mistakes :o