0

What I need to do is to receive an array a number and the index.And I try to create a function *insertc(char str, char c, int n) but it seems that the loop has some problems that it couldnot to append and somehow export an irregular row.Like this.Help me!

#include<stdio.h>
char str[10];
void insertc(char *str, char c, int n)
{   int m=sizeof(str)+1;
    char *p=str;
    for(int i=m-1;i>n-1;i--)
    str[i+1]=str[i];
    *(p+n-1)=c;
}
int main(){
    char c;int a;
    gets(str);
    scanf("%c\n%d",&c,&a);
    insertc(str,c,a);
    puts(str);
    return 0;
}
  • 1
    I *guarantee* `sizeof(str)` does not do what you think it does in this context. See here: [How to find the 'sizeof' (a pointer pointing to an array)?](https://stackoverflow.com/questions/492384/how-to-find-the-sizeof-a-pointer-pointing-to-an-array). And take note, if you're wondering how `gets` (later in your code) magically can do this, the answer is, *it cannot*, and that is the reason why that function is considered so evil it was removed from the language standard library. – WhozCraig Jul 19 '21 at 02:46
  • Welcome to Stack Overflow. Please look over our [help section](https://stackoverflow.com/help/), with special attention to the page on [minimal complete examples](https://stackoverflow.com/help/minimal-reproducible-example). Remove the user input code, and hard-code an example. Tell us the result you want and the result you get. – Beta Jul 19 '21 at 02:48
  • Oh, and please replace pictures of text with the actual text. – the busybee Jul 19 '21 at 06:33

2 Answers2

0

Replace *(p+n-1)=c; with *(p+n)=c;.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Itati
  • 193
  • 11
  • 2
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Jul 19 '21 at 05:37
0

This is an explanation for what Itati proposed:

  • p points to the start of the array i.e, index 0. Assume n = 2 i.e, you want to insert something at index 2 of the array. So to do that, you need to add 2 to p i.e., p now needs to point to the memory holding index 2 of the array.
HiEd
  • 160
  • 3