gpt4 book ai didi

c - 堆栈溢出与 C 中的指针

转载 作者:太空狗 更新时间:2023-10-29 15:24:57 25 4
gpt4 key购买 nike

我是 C 语言的新手,我正在尝试一些我发现的练习。

在其中一个练习中,我尝试使用指向字符串(字符数组)的指针,但它不起作用。它会编译,但在执行时会抛出“堆栈溢出”(好吧,我认为是“堆栈溢出”,因为我有西类牙语版本)。

这些是有问题的行:

//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 de segmento”,谷歌说这意味着 Stack Overflow

#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”。第二个评论显示它崩溃的地方

感谢您的快速回答!!

最佳答案

while 循环之前的代码很好,因为它可以正确编译和运行(据我所知)

但是 while 循环有一个错误,我不确定它在你的情况下是如何编译的。因为你写了

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

编译器错误为

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

你必须将“\0”转换为“\0”

关于c - 堆栈溢出与 C 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7433973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com