Reputation: 79
Visual Studio tells me the problem with my code is in the line where
*p = *p1;
But I don't see what's wrong there.
The objective in this code is to build a function that will get a string and an int and will sort the string and return the letter in the index of the int.
For example for the string "build" it will sort it to "bdilu" if the int was 2 would return "i".
Here is the code I wrote:
#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];
}
And this is the error:
Unhandled exception at 0x00F81436 in justforstudy.exe: 0xC0000005:
Access violation writing location 0x00F85859.
Upvotes: 1
Views: 4046
Reputation: 210878
You pass a string literal to your function letterAtIndex
. you can't write to it. Change char *arr = { "a string" };
to char arr[] = { "a string" };
and it will work.char arr[]
is an array of elemts with type char
which is read and writeable:
int main(){
char arr[] = { "a string" };
char s = letterAtIndex( arr, 7 );
printf( "%c", s );
return 0;
}
An other possibility would be to allocate dynamic memory and copy the string into it.
#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;
}
Upvotes: 3
Reputation: 8657
It's undefined behaviour to attempt changing a string literal. Use the type const char *
for variables pointing to string literals to have the compiler help you spot when you attempt to do so.
You can fix your code by:
arr
as char arr[]
Upvotes: 2