2011-09-15 125 views
4

我是C新手,我正在尝试一些我发现的练习。C中指针堆栈溢出

在其中一个练习中,我试图使用指向字符串(char数组)的指针,但它不起作用。它编译,但执行时,它会抛出“堆栈溢出”(嗯,我认为是“堆栈溢出”,因为我用西班牙文)。

这是有问题的线路:

//This is the variable declaration, before this, there is the "main function" declaration 
char entrada[100]; 
char *ult=entrada; 
char cantidadstr[10]; 
int i,j,k = 0; 
int res; 

scanf ("%s",entrada); 
printf ("\n%s",entrada); 

//Here crashes 
printf ("Hola %s",ult); 
while (*ult != "\0"){ 

//And here there's more code 

预先感谢您!

编辑

(我不能回答我:)) 然后,我会发布更多的代码。

当我执行,插入数据后,它会抛出“Violación德SEGMENTO”,和谷歌说,这意味着堆栈溢出

#include <string.h> 
#include <stdio.h> 
#include <stdlib.h> 

int main(void){ 
char entrada[1001*11*101]; 
/*Asi tenemos el tamano maximo: 
1001 por las 1000 posibles lineas, mas la primera 
11 por el tamano maximo del numero (1 + 9 ceros), mas el espacio o salto de linea siguiente 
101 por el numero de numeros por linea, mas el primero 
*/ 
char *ult=entrada; 
char cantidadstr[10]; 
int i,j,k = 0; 
int res; 

memset (entrada,'\0',1001*11*101); 
scanf ("%s",entrada); 
printf ("\n%s",entrada); 


//poniendo ese print ahi arriba, ese me lo muestra, por tanto, el fallo esta en el puntero de debajo de esta linea 
printf ("Hola %s",ult); 
while (*ult != "\0"){ 
    if(*ult == "\n"){ 
     if(i != 0){ 
      printf("\n"); 
     } 
     i++; 
     j = 0; 
    } 
    else if(i != 0){ 
     if(*ult == " "){ 
      j++; 
      k=0; 
      res = atoi(cantidadstr); 
      printf("%d ",res*2); 
      //Este es el otro cambio que hablaba 
      cantidadstr[10] = '\0';    
     } 
     else if(j != 0){ 
      cantidadstr[k] = *ult; 
     } 

    } 
    k++; 
    *ult++; 
} 
return 0; 

}

这是准确和完整的代码,并在评论西班牙语为另一个论坛。 “entrada”的大小对于练习中发送的任何数据都足够大。 “memset”只是添加。第二个评论显示它崩溃的地方

感谢您的快速回答!

+0

您是否可能在scanf中输入了超过100个字符的输入内容?我也希望看到确切的错误,即使是西班牙文,但谷歌翻译是你的朋友在那里。 –

+0

不应该崩溃到那里,除非你输入的字符串超过99个字符... – Torp

+0

好吧,如果5分钟后,我们没有正面答案,我会说“发布更多的代码”,因为有在其他地方可能会破坏造成问题的记忆的可能性很大。 –

回答

5

while循环之前的代码是好的,因为它编译并运行正常(只要我能想到的)

但while循环有一个错误我不知道它在你的情况如何编译。 因为你已经写

while (*ult != "\0"){

这给作为

*ult is of type char 
"\0" is of type const char* 

你要转换 “\ 0” '\ 0'

+1

这工作!非常感谢你。我不知道这是两者之间的差异!我喜欢这个论坛,这是第一次,但我会多用几次:D再次感谢! – markmb

+0

尝试在编译时使用警告,例如。用gcc add -Wall –

2

以下行编译器错误:

cantidadstr[10] = '\0'; 

将写过的末尾,这绝对是不好的,最有可能导致你的堆栈溢出。如果您要终止cantidadstr,请使用cantidadstr[9]= '\0';。 C中的数组是基于零的,不是基于数组的,所以大小为N的数组的第一个元素开始于[0]并且最后的可参考元素是[N-1]

+0

可能还提到他实际上想要cantidadstr [k] ='\ 0';它应该在atoi之前。 –

+0

这是一个已知的错误,我想清理变量,但我确定问题不在那里。谢谢 – markmb