gpt4 book ai didi

c - 在 C : Unhandled exception : 0xC0000005: Access violation writing location. 程序不会运行

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:53 25 4
gpt4 key购买 nike

Visual Studio 告诉我代码的问题在于

*p = *p1;

但我不明白那里有什么问题。
此代码的目标是构建一个函数,该函数将获取一个字符串和一个 int,并对字符串进行排序并返回 int 索引中的字母。
例如,对于字符串“build”,如果 int 为 2,它将把它排序为“bdilu”,将返回“i”。这是我写的代码:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
char letterAtIndex(char *s, int n);

void main(){
char s, *arr = { "a string" };
s=letterAtIndex(arr, 7);
printf("%c", s);
getch();
}
char letterAtIndex(char *s, int n){
int t;
char *p1 = s, *p2 = s, *p;
while (*(++p2));
while (p1 < p2){
p = p1;
while (p < p2){
if (*p1>*p){
t = *p;
*p = *p1;
*p1 = t;
}
p++;
}
p1++;
}
return s[n];
}

这是错误:

Unhandled exception at 0x00F81436 in justforstudy.exe: 0xC0000005: 
Access violation writing location 0x00F85859.

最佳答案

您将字符串文字传递给函数 letterAtIndex。你不能写信给它。将 char *arr = { "a string"}; 更改为 char arr[] = { "a string"}; 即可。char arr[ ]char 类型的元素数组,可读写:

int main(){
char arr[] = { "a string" };
char s = letterAtIndex( arr, 7 );
printf( "%c", s );
return 0;
}

另一种可能性是分配动态内存并将字符串复制到其中。

#include <string.h> // strcpy
#include <malloc.h> // malloc, free

int main(){
const char *str = "a string";
char *arr = malloc( strlen(str ) + 1 );
strcpy( arr, str );
char s = letterAtIndex( arr, 7 );
printf( "%c", s );
free( arr );
return 0;
}

关于c - 在 C : Unhandled exception : 0xC0000005: Access violation writing location. 程序不会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251859/

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