+ Post New Thread
Results 1 to 4 of 4
-
10th November 2018, 16:22 #1
- Join Date
- Jul 2016
- Posts
- 17
- Helped
- 0 / 0
- Points
- 523
- Level
- 4
error with pointer as string
Hi freinds,
I want to write five 'M' in a string. I have defined string by char * as following code:
Code:#include <stdio.h> #include <stdlib.h> int main() { char *str; int i=0; while(i<5) { *(str+i) = 'M'; i++; } *(str+5) = '\0'; printf("%s", str); return 0; }
what's my problem? can anybody help?
tnxLast edited by KlausST; 10th November 2018 at 16:29. Reason: added code tags
-
Advertisement
-
10th November 2018, 19:05 #2
- Join Date
- Jul 2010
- Location
- Sweden
- Posts
- 1,021
- Helped
- 388 / 388
- Points
- 7,616
- Level
- 20
Re: error with pointer as string
"char str[5]" reserves 5 bytes of memory for the string.
The first is str[0] = *(str + 0) and the last is str[4] = *(str + 4).
You write to *(str + 5) which is outside the array. It it pure luck that it works.
"str" is not a pointer, it is the start address of the array. "str" behaves almost like a pointer, but you can't assign a value to it.
"char *str" only defines only the pointer, no space for the characters.
A function local variable of type "auto" (default) has random/unknown data before a value is assigned.
When you do *(str + i) = 'M' you write to a random address.
You can do this to make the pointer version to work:
char my_string[6];
char *str = my_string;
1 members found this post helpful.
-
Advertisement
-
11th November 2018, 12:44 #3
- Join Date
- Jul 2016
- Posts
- 17
- Helped
- 0 / 0
- Points
- 523
- Level
- 4
Re: error with pointer as string
Last edited by kahroba92; 11th November 2018 at 12:45. Reason: adding quote
-
Advertisement
-
11th November 2018, 16:46 #4
- Join Date
- Jan 2008
- Location
- Bochum, Germany
- Posts
- 45,795
- Helped
- 13920 / 13920
- Points
- 262,035
- Level
- 100
Re: error with pointer as string
C text book (Kernighan/Ritchie) says both are equivalent. They prefer char *, indicating the pointer nature. In the examples, array notation is used where the function argument is accessed as character array and pointer notation with pointer access. But actually, both styles can be mixed.
Code C - [expand] 1 2 3 4 5 6 7
void copy(char to[], char from[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; }
Code C - [expand] 1 2 3 4 5 6 7
int strlen(char *s) { int n; for (n = 0; *s != '\0', s++) n++; return n; }
1 members found this post helpful.
+ Post New Thread
Please login