strcat и ошибка сегментации 11

мой код выглядит следующим образом:

   #include<stdio.h>
   #include <string.h>
   #include <math.h>
   #include <stdlib.h>
   int string_length(char*);
   void reverse(char*);
   int main(void)
   {
      char num[256];
      printf("%c[%d;%d;%dmPlease enter a number of rows: ", 0x1B, 5, 32, 40);
      gets(num);
      //gets number

printf("%c[%dm\n", 0x1B, 0);
//Resets color

//Variables
char revnum[50], q[50] = "\0", r[50] = "\v";
int i, x, j, z, w;

//Reverses inputted character string
reverse(num);

//Takes reversed inputted character string and out puts it as an integer
for(i = 0; num[i] != '\0'; ++i) {
    j = -(48-num[i]);
    double y = i;
    x = j*pow(10, y) + x;
}

//Takes integer version of inputted character string and assigns a counter's value (counting up to our integer version) to a character string
for (z = 0; z <= x; z++) {
    sprintf(revnum, "%d", z);

    //Takes the new character string for each number up to the inputted value and prints it vertically, but no differentiating between numbers and printing them horizontally to each other
    for (w = 0; revnum[w] != '\0'; ++w) {
        strcat(q, r);
        printf("%s", q);
        strcat(q, revnum[w]);
      }
   }

  }

  //Function which reverses a character string
   void reverse(char *num)
{
int length, c;
char *begin, *end, temp;

length = string_length(num);

begin = num;
end = num;

for ( c = 0 ; c < ( length - 1 ) ; c++ )
    end++;

for ( c = 0 ; c < length/2 ; c++ )
{
    temp = *end;
    *end = *begin;
    *begin = temp;

    begin++;
    end--;
}
}

 int string_length(char *pointer)
 {
int c = 0;

while( *(pointer+c) != '\0' )
    c++;

return c;
}

смысл программы состоит в том, чтобы вывести все числа перед числом, введенным с цифрами каждого числа по вертикали, а затем с самими числами, перечисленными по горизонтали.

пожалуйста помоги!!!


person Bryan James    schedule 20.02.2013    source источник
comment
Попробуйте запустить программу в отладчике. Это поможет вам, сообщив вам, где произошел сбой, позволит вам пройтись по стеку вызовов функций, чтобы вы могли увидеть, как вы там оказались, и позволит вам изучить переменную, чтобы помочь вам понять причину.   -  person Some programmer dude    schedule 20.02.2013
comment
Однако есть пара моментов: зачем создавать собственную функцию длины строки, если strlen вполне подойдет? И вместо того, чтобы зацикливаться, чтобы найти конец строки в reverse, вы можете просто добавить (length - 1) к указателю.   -  person Some programmer dude    schedule 20.02.2013
comment
Однако основная проблема может заключаться в том, что вы не инициализируете все используемые вами переменные. Если вы используете, например. опция -Wall для GCC при компиляции вы получите предупреждение об этом.   -  person Some programmer dude    schedule 20.02.2013
comment
Вы должны получать по крайней мере одно предупреждение компилятора от вашего компилятора. Если да, исправьте свой код, пока он не скомпилируется чисто. Если нет, узнайте, как повысить уровень предупреждения вашего компилятора. strcat(q, revnum[w]); передает char в качестве второго аргумента strcat; для этого требуется char*. И никогда не используйте функцию gets(); это по своей сути небезопасно.   -  person Keith Thompson    schedule 20.02.2013
comment
string_length? Есть ли какая-то проблема со стандартным C strlen(), о которой мы все не знали последние 30 лет? :-)   -  person paxdiablo    schedule 20.02.2013
comment
Если вы выполняете man strcat в терминале, спецификация говорит: char *strcat(char *dest, const char *src); Попробуйте strcat(q, &revnum[w]); В общем, если использовать char q[50]; char *r = привет, strcat(q,r), который вы сделали, отлично работает.   -  person Shobhit Puri    schedule 20.02.2013


Ответы (1)


Вы сделали несколько ошибок. Этот код работает:

#include<stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int string_length(char*);
void reverse(char*);
int main(void)
{
  char num[256];
  printf("Please enter a number of rows: ", 0x1B, 5, 32, 40);
  gets(num);
  //gets number

//Variables
char revnum[50], q[50] = "\0";
int i, x, j, z, w;

//Reverses inputted character string
reverse(num);

//Takes reversed inputted character string and out puts it as an integer
x = atoi(num);

//Takes integer version of inputted character string and assigns a counter's value (counting up to our integer version) to a character string
for (z = 0; z <= x; z++) {
sprintf(revnum, "%d", z);

//Takes the new character string for each number up to the inputted value and prints it vertically, but no differentiating between numbers and printing them horizontally to each other
for (w = 0; revnum[w] != '\0'; ++w) {
    printf("%s\v", q);
char a[2];
sprintf(a,"%c",revnum[w]);
strcat(q,a);
  }
}

}

//Function which reverses a character string
void reverse(char *num)
{
int length, c;
char *begin, *end, temp;

length = string_length(num);

begin = num;
end = num;

for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;

for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;

 begin++;
 end--;
}
}

int string_length(char *pointer)
{
int c = 0;

while( *(pointer+c) != '\0' )
c++;

return c;
}

И скомпилируйте с параметром -fno-stack-protector, чтобы предотвратить обнаружение повреждения стека.

person A. Mikhaylov    schedule 20.02.2013